Python generate CSV file from List or Dictionary

CSV (Comma Separated Values) is the most common data format for one-time data export from one system to another. The original data can be in any other relational database such as DB2, MySql, SQL Server, etc. but you can easily dump that into a CSV format and pass it on. I would say before the days of XML and JSON it was the de facto format for data transport. Python makes it really easy to create a CSV file with various formats using dialect and/or formatting parameters. In this example we learn how to create a simple text file and CSV files from both list and dictionary as input data.

Python generate CSV file from List and Dictionary data

Source code for the Python module

import os
import csv

def createTextFile():
    try:
        myFilePath = os.path.join(filePath, 'SimpleFile.txt')
        with open(myFilePath,'w') as myFile:
            myFile.write("This is a Simple Text file\n")
            myFile.write("This is line number 1\n")
            
            myList = ["This is line number 2\n",
                      "This is line number 3\n",
                      "This is line number 4\n"]
            myFile.writelines(myList)
    except IOError as (errno, strerror):
        print("I/O error({0}): {1}".format(errno, strerror)) 
        
    return

def fromListToCSV():
    
    headings = ['ID','Name','CountryCode','District','Population']
    myListData = [[3793,"New York","USA","New York",8008278],
                [3794,"Los Angeles","USA","California",3694820],
                [3795,"Chicago","USA","Illinois",2896016],
                [3796,"Houston","USA","Texas",1953631],
                [3797,"Philadelphia","USA","Pennsylvania",1517550]]
    try:
        myFilePath = os.path.join(filePath, 'MyList.csv')
        with open(myFilePath,'w', newline='') as myCSVFile:
            csvWriter = csv.writer(myCSVFile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            csvWriter.writerow(headings)
            for data in myListData:
                csvWriter.writerow(data)
    except IOError as (errno, strerror):
        print("I/O error({0}): {1}".format(errno, strerror))  
        
    return

def fromDictToCSV():
    
    headings = ['ID','Name','CountryCode','District','Population']
    myDictData = [{'ID': '3793', 'CountryCode': 'USA', 'Population': '8008278', 'District': 'New York', 'Name': 'New York'},
        {'ID': '3794', 'CountryCode': 'USA', 'Population': '3694820', 'District': 'California', 'Name': 'Los Angeles'},
        {'ID': '3795', 'CountryCode': 'USA', 'Population': '2896016', 'District': 'Illinois', 'Name': 'Chicago'},
        {'ID': '3796', 'CountryCode': 'USA', 'Population': '1953631', 'District': 'Texas', 'Name': 'Houston'},
        {'ID': '3797', 'CountryCode': 'USA', 'Population': '1517550', 'District': 'Pennsylvania', 'Name': 'Philadelphia'}]
    try:
        myFilePath = os.path.join(filePath, 'MyDictionary.csv')
        with open(myFilePath,'w', newline='') as myCSVFile:
            csvWriter = csv.DictWriter(myCSVFile, fieldnames=headings, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            csvWriter.writeheader()
            for data in myDictData:
                csvWriter.writerow(data)
    except IOError as (errno, strerror):
        print("I/O error({0}): {1}".format(errno, strerror)) 
        
    return

if __name__ == '__main__':
    pass #path for the current file
    currentPath = os.path.dirname(__file__)
    #path for the filename that we want to read
    filePath = os.path.abspath(os.path.join(currentPath, os.pardir,os.pardir,'data'))
    #write a simple Text file
    createTextFile()
    #write a CSV file from List
    fromListToCSV()
    #write a CSV file from Dictionary
    fromDictToCSV()

Reference

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.