CSV库还有其他处理CSV的方法,这里只是介绍几个常用的,后面如果用到别的会进行更新
目录
1 生成一个新的csv文件,并向其中写一点东西
import csv
with open('test.csv','w',newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['a','b','c'])
writer.writerow(['d','e'])
- writerow()调用一次就会写一行
运行后在代码的同级目录中会出现生成的csv文件
双击打开后发现内容已经写在里面了
如果你不写newline的话就会有几个空行
import csv
with open('test.csv','w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['f','g','h'])
writer.writerow(['i','g','k','l'])
writer.writerow(['1','2','3','4'])
2 单纯往里面写几行
用open的追加模式 a
import csv
with open('test.csv','a',newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['f','g','h'])
writer.writerow(['i','g','k','l'])
writer.writerow(['1','2','3','4'])
3 读取csv文件
import csv
with open('test.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)