首页IT科技python5种数据类型(python中不同的CSV功能和使用)

python5种数据类型(python中不同的CSV功能和使用)

时间2025-05-27 22:49:01分类IT科技浏览5402
导读:在之前的文章中介绍过为什么python学习中会使用CSV文件格式?这边文章将会详细介绍python中不同的CSV功能和使用。...

在之前的文章中介绍过为什么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:#Openanewfilenamednew_titanic.csvunderwritemode 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:#openanewfilenew_titanic,csvunderwritemode writer=csv.DictWriter(new_csv_file,fieldnames=fields) writer.writeheader()#writingtheheaders(fieldnames) writer.writerows(mydict)#writingdatarows

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
长期优质seo接单服务怎么做(长期优质SEO接单服务) domexception blocked a frame(DOMException: Failed to execute ‘insertBefore‘ on ‘Node‘: The node before which the new node …报错)