python中有一个读写csv文件的包,直接import csv即可
新建test.csv
1.写
import csv with open("test.csv","w",encoding=‘utf8‘) as csvfile: writer=csv.writer(csvfile) writer.writerow(["index","a_name","b_name"]) writer.writerows([[0,‘a1‘,‘b1‘],[1,‘a2‘,‘b2‘],[2,‘a3‘,‘b3‘]])
直接使用这种写法会导致文件每一行后面会多一个空行
解决的方法
用python3来写wirterow时,打开文件时使用w模式,然后带上newline=‘‘
import csv with open("test.csv","w",encoding=‘utf8‘,newline=‘‘) as csvfile: writer=csv.writer(csvfile) writer.writerow(["index","a_name","b_name"]) writer.writerows([[0,‘a1‘,‘b1‘],[1,‘a2‘,‘b2‘],[2,‘a3‘,‘b3‘]])
2.读
import csv with open("test.csv","r") as csvfile: reader=csv.reader(csvfile) for line in reader: print(line)