分享

Dictionary to CSV & List to CSV in Python

 dbn9981 2016-09-16

Why CSV?

CSV (Comma Separated Values) is a most common file format that is widely supported by many platforms and applications. It is easier to export data as a csv dump from one system to another system. In Python it is easier to read data from csv file and export data to csv. csv package comes with very handy methods and parameters to read write data.

Read CSV file as Dictionary in Python

CSV File Example:

read csv file

Define correct path of the csv file in `csv_file` variable.

csv-to-dict.py
import csv
import os

def ReadCSVasDict(csv_file):
    try:
        with open(csv_file) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                print row['Row'], row['Name'], row['Country']
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return

currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"

ReadCSVasDict(csv_file)

Generate CSV from Dictionary in Python

Define correct path of the csv file in csv_file variable, CSV column names and dict data.

dict-to-csv.py
import csv
import os

def WriteDictToCSV(csv_file,csv_columns,dict_data):
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return            

csv_columns = ['Row','Name','Country']
dict_data = [
    {'Row': 1, 'Name': 'Alex', 'Country': 'India'},
    {'Row': 2, 'Name': 'Ben', 'Country': 'USA'},
    {'Row': 3, 'Name': 'Shri Ram', 'Country': 'India'},
    {'Row': 4, 'Name': 'Smith', 'Country': 'USA'},
    {'Row': 5, 'Name': 'Yuva Raj', 'Country': 'India'},
    ]

currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"

WriteDictToCSV(csv_file,csv_columns,dict_data)

Combined Snippet - Read Write Dictionary - CSV

read-write-csv.py
import csv
import os

def ReadCSVasDict(csv_file):
    try:
        with open(csv_file) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                print row['Row'], row['Name'], row['Country']
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return

def WriteDictToCSV(csv_file,csv_columns,dict_data):
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for data in dict_data:
                writer.writerow(data)
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return            

csv_columns = ['Row','Name','Country']
dict_data = [
    {'Row': 1, 'Name': 'Alex', 'Country': 'India'},
    {'Row': 2, 'Name': 'Ben', 'Country': 'USA'},
    {'Row': 3, 'Name': 'Shri Ram', 'Country': 'India'},
    {'Row': 4, 'Name': 'Smith', 'Country': 'USA'},
    {'Row': 5, 'Name': 'Yuva Raj', 'Country': 'India'},
    ]

currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"

WriteDictToCSV(csv_file,csv_columns,dict_data)

ReadCSVasDict(csv_file)

Read CSV file as Lists in Python

CSV File Example:

read csv file Define correct path of the csv file in csv_file variable. We may perform some additional operations like append additional data to list, removing csv headings(1st row) by doing a pop operation on the list like below.</p>

csv-to-list.py
import csv
import os

def ReadCSVasList(csv_file):
    try:
        with open(csv_file) as csvfile:
            reader = csv.reader(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            datalist = []
            datalist = list(reader)
            return datalist
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return        


currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"

csv_data_list = ReadCSVasList(csv_file)
print csv_data_list

# To Ignore 1st Row (Headers)          
csv_data_list.pop(0)
print csv_data_list

# append to list
csv_data_list.append(['6', 'Suresh', 'India'])

print csv_data_list

Generate CSV from List in Python

Define correct path of the csv file in csv_file variable, CSV column names and list data.

csv-to-list.py
import csv
import os

def WriteListToCSV(csv_file,csv_columns,data_list):
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            writer.writerow(csv_columns)
            for data in data_list:
                writer.writerow(data)
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return              

csv_columns = ['Row','Name','Country']
csv_data_list = [['1', 'Alex', 'India'], ['2', 'Ben', 'USA'], ['3', 'Shri Ram', 'India'], ['4', 'Smith', 'USA'], ['5', 'Yuva Raj', 'India'], ['6', 'Suresh', 'India']]

currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"


WriteListToCSV(csv_file,csv_columns,csv_data_list)

Combined Snippet - Read Write List - CSV

read-write-csv-list.py
import csv
import os

def ReadCSVasList(csv_file):
    try:
        with open(csv_file) as csvfile:
            reader = csv.reader(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            datalist = []
            datalist = list(reader)
            return datalist
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return

def WriteListToCSV(csv_file,csv_columns,data_list):
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.writer(csvfile, dialect='excel', quoting=csv.QUOTE_NONNUMERIC)
            writer.writerow(csv_columns)
            for data in data_list:
                writer.writerow(data)
    except IOError as (errno, strerror):
            print("I/O error({0}): {1}".format(errno, strerror))    
    return              

csv_columns = ['Row','Name','Country']

currentPath = os.getcwd()
csv_file = currentPath + "/csv/Names.csv"

csv_data_list = ReadCSVasList(csv_file)
print csv_data_list

# To Ignore 1st Row (Headers)          
csv_data_list.pop(0)
print csv_data_list

# append to list
csv_data_list.append(['6', 'Suresh', 'India'])

print csv_data_list


WriteListToCSV(csv_file,csv_columns,csv_data_list)

Download

Dict to CSV List to CSV

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多