赞
踩
Python 天生支持读取CSV 格式数据并且是可配置的。
1、导入模块
import csv
2、Python CSV 方法
| 方法 | 描述 |
|---|---|
csv.reader | 返回一个遍历 CSV 文件各行的读取器对象 |
csv.writer | 返回将数据写入 CSV 文件的写入器对象 |
import csv
with open('test1.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
for row in reader:
print(str(row))
假设 ‘test1.csv’ 里边的内容为:
1. ['my first column', 'my second column', 'my third column']
2. ['my first column 2', 'my second column 2', 'my third column 2']
那么我们运行这个代码后,相应的输出:
['my first column', 'my second column', 'my third column']
['my first column 2', 'my second column 2', 'my third column 2']
csv.writer()方法返回一个 writer 对象,该对象将用户数据转换为给定文件对象上的定界字符串。writerow()将一个列表全部写入csv的同一行。writerows()方法将所有给定的行写入csv 文件。生成和读取一样的简单
import csv
rows = [['1', '2', '3'], ['4', '5', '6']]
csv_file=open('my.csv', 'w', newline='')
with csv_file:
writer = csv.writer(csv_file)
for row in rows:
writer.writerow(row)
在my.csv 文件的数据会是:
1,2,3
4,5,6
输出的内容:
['1', '2', '3']
['4', '5', '6']
writerow()将一个列表全部写入csv的同一行。
import csv
csv_list = ['a','b','c','d']
csvfile=open('D:/AllKindsOfWords/test/test.csv', 'w',newline = '')
writer = csv.writer(csvfile)
writer.writerow(csv_list)
结果:

writerows()将一个二维列表中的每一个列表写为一行。
import csv
csv_list = ['a','b','c','d']
csvfile=open('D:/AllKindsOfWords/test/test.csv', 'w',newline = '')
writer = csv.writer(csvfile)
writer.writerows(csv_list)
结果:

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。