打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Dictionary to CSV & List to CSV in Python

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:

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

csv-to-dict.py
import csvimport osdef 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))        returncurrentPath = 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 csvimport osdef 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 csvimport osdef 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))        returndef 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:

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 csvimport osdef 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 listcsv_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 csvimport osdef 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 csvimport osdef 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))        returndef 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 listcsv_data_list.append(['6', 'Suresh', 'India'])print csv_data_listWriteListToCSV(csv_file,csv_columns,csv_data_list)

Download

Dict to CSVList to CSV

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[接口测试 - 基础篇] 09 其实吧,读写csv格式也是要掌握的
Python处理CSV、JSON和XML数据的简便方法
python读写csv文件
数据分析之在线JupyterNotebook使用小技巧|Python技能树测评
fopen file
Python 读取csv的某行
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服