700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python:使用 csv 模块读写 csv 文件

Python:使用 csv 模块读写 csv 文件

时间:2022-10-08 02:47:41

相关推荐

Python:使用 csv 模块读写 csv 文件

目录

一、读取csv 文件

二、写入 csv 文件

一、读取csv 文件

# -*- coding: utf-8 -*-import csvimport sysdef read_csv_file(filename):with open(filename, 'r') as f:csv_reader = csv.reader(f)header_row = next(csv_reader)print(header_row) # 输出文件头cnt = 0for line in csv_reader: # 循环遍历文件的每一行数据cnt += 1print("line [{4}] : {0},{1},{2},{3}".format(line[0], line[1], line[2], line[3], cnt))if "__main__" == __name__:filename = sys.argv[1]read_csv_file(filename)

执行读取脚本的效果如下(file-list.csv 文件有11行数据,第一行是 csv 文件头,其余行是数据):

$ python read-csv-file.py file-list.csv ['名称', '大小', '路径', '修改时间']line [1] : Security.evtx,391122944,C:\Windows\System32\winevt\Logs,-02-24 07:23:48line [2] : MRT.exe,133326408,C:\Windows\System32,-12-24 21:45:48line [3] : MRT-KB890830.exe,133326408,C:\Windows\System32,-12-24 21:45:50line [4] : NvCplSetupInt.exe,97078976,C:\Windows\System32\DriverStore\FileRepository\nvdmwu.inf_amd64_26aa6356770b2e86,-09-12 21:15:30line [5] : SOFTWARE,86245376,C:\Windows\System32\config,-02-20 09:31:27line [6] : SOFTWARE,86077440,C:\Windows\System32\config\RegBack,-02-21 01:32:16line [7] : SRUDB.dat,79495168,C:\Windows\System32\sru,-02-24 21:20:00line [8] : RCORES64.dat,72520616,C:\Windows\System32,-04-08 04:44:38line [9] : RCORES64.dat,72130584,C:\Windows\System32\DriverStore\FileRepository\hdxsgma4.inf_amd64_67e758791d8608ce,-08-04 00:21:58line [10] : BootCKCL.etl,48234496,C:\Windows\System32\WDI\LogFiles,-02-20 09:33:51

二、写入 csv 文件

# -*- coding: utf-8 -*-import csvimport sysdef write_csv_file(filename):with open(filename, 'w') as f:csv_writer = csv.writer(f)csv_writer.writerow(['type', 'name', 'age'])for i in range(5):csv_writer.writerow(['dog' + str(i), 'dog-' + str(i), str(i)])rows = list()for i in range(6, 10):rows.append(['dog' + str(i), 'xdog,-' + str(i), str(i)]) # name 字段中包含了逗号(,)csv_writer.writerows(rows)if "__main__" == __name__:filename = sys.argv[1]write_csv_file(filename)

执行写入脚本的效果如下:

$ python write-csv-file.py dogs.csv$ cat dogs.csv type,name,agedog0,dog-0,0dog1,dog-1,1dog2,dog-2,2dog3,dog-3,3dog4,dog-4,4dog6,"xdog,-6",6dog7,"xdog,-7",7dog8,"xdog,-8",8dog9,"xdog,-9",9

可以发现,当 csv 行的内容部分包含逗号(,)的时候,这个字段会被双引号修饰。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。