python 包之 csv 文档操作教程
一、读取数据
-
编码一定要和写入编码一样
import csv
with open("ceshi.csv","r",encoding="GBK") as f:
reader = csv.reader(f)
for i in reader:
print(i)
二、单行写入数据
-
如果不加newline这个csv文件会出现空白行
-
通过writerow添加单行数据
import csv
with open("ceshi.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(['姓名','年龄','性别'])
writer.writerow(['autofelix','25','女'])
writer.writerow(['飞兔', '27', '男'])
三、多行写入数据
-
通过writerows可以一次写入多行数据
import csv
with open("ceshi.csv", "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(['姓名','年龄','性别'])
writer.writerows([['autofelix','25','女'], ['飞兔', '27', '男']])
四、写入字典形式
-
通过字典格式写入数据
import csv
with open("ceshi.csv", "w", newline='') as f:
filedump = ['姓名','年龄','性别']
writer = csv.DictWriter(f,fieldnames=filedump)
writer.writeheader()
writer.writerow({'姓名':'autofelix','年龄':'25','性别':'女'})
writer.writerow({'姓名': '飞兔', '年龄': '27', '性别': '男'})