在之前的文章中介绍过为什么python学习中会使用CSV文件格式?这边文章将会详细介绍python中不同的CSV功能和使用。
一、CSV模块功能
在CSV模块下,可以找到以下功能
二、Python中CSV文件操作
加载CSV文件后,您可以执行多种操作。将在Python中显示对CSV文件的读取和写入操作
在Python中读取CSV文件:
importcsv withopen('Titanic.csv','r')ascsv_file:#Opensthefileinreadmode csv_reader=csv.reader(csv_file)#Makinguseofreadermethodforreadingthefile forlineincsv_reader:#Iteratethroughthelooptoreadlinebyline print(line)
用Python写入CSV文件:
importcsv withopen('Titanic.csv','r')ascsv_file: csv_reader=csv.reader(csv_file) withopen('new_Titanic.csv','w')asnew_file:#Openanewfilenamed'new_titanic.csv'underwritemode csv_writer=csv.writer(new_file,delimiter=';')#makinguseofwritemethod forlineincsv_reader:#foreachfileincsv_reader csv_writer.writerow(line)#writingouttoanewfilefromeachlineoftheoriginalfile
读取CSV文件作为字典
importcsv withopen('Titanic.csv','r')ascsv_file:#Openthefileinreadmode csv_reader=csv.DictReader(csv_file)#usedictreadermethodtoreadethefileindictionary forlineincsv_reader:#Iteratethroughthelooptoreadlinebyline print(line)
importcsv mydict=[{'Passenger':'1','Id':'0','Survived':'3'},#key-valuepairsasdictionaryobj {'Passenger':'2','Id':'1','Survived':'1'}, {'Passenger':'3','Id':'1','Survived':'3'}] fields=['Passenger','Id','Survived']#fieldnames filename='new_Titanic.csv'#nameofcsvfile withopen('new_Titanic.csv','w')asnew_csv_file:#openanewfile'new_titanic,csv'underwritemode writer=csv.DictWriter(new_csv_file,fieldnames=fields) writer.writeheader()#writingtheheaders(fieldnames) writer.writerows(mydict)#writingdatarows