在之前的文章中,我介绍了为什么CSV文件格式用于python学习?本文将详细介绍python中不同的CSV功能和用途。
一、CSV模块功能
以下功能可以在CSV模块下找到。
二、PythonCSV文件操作
加载CSV文件后,您可以执行多种操作。CSV文件的读写将显示在Python中
读取Python中的CSV文件:
importcsv withopen('Titanic.csv','r')ascsv_file:#Opensthefileinreadmode csv_reader=csv.reader(csv_file)#Makinguseofreadermethodforreadingthefile forlineincsv_reader:#Iteratethroughthelooptoreadlinebyline print(line)
将CSV文件写入Python:
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)
CSV文件作为字典写入
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