python中不同的CSV功能和使用

在之前的文章中介绍过为什么python学习中会使用CSV文件格式?这边文章将会详细介绍python中不同的CSV功能和使用。

一、CSV模块功能

在CSV模块下,可以找到以下功能

python中不同的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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。