python 处理 csv 文件
csv 文件是一种逗号分隔的纯文本形式存储的表格数据,Python内置了CSV模块,可直接通过该模块实现csv文件的读写操作,在web应用中导出数据是比较常见操作。
这篇文章介绍csv模块的基本用法
写操作
writer.writerow, 将多列数据写入一行
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["123", "234", "345"])
writer.writerow(["abc", "efg", "hij"])
如果以文本文件的方式打开,每行数据之间都是用逗号隔开的文本字符串
写入时,必须指定 newline=’’, 否则每插入一行就有一个空行
读操作
with open('some.csv', 'r', newline="") as f:
reader = csv.reader(f)
for row in reader:
print(row)
输出
['123', '234', '345']
['abc', 'efg', 'hij']
DictWriter & DictReader
csv.DictWriter 对象引入了一个fieldnames参数, fieldnames是csv文件中的表头,就是第一行中的数据
with open("person.csv", 'w', newline='') as f:
fieldnames = ["name", "age", "sex"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"name": "zhangsan", "age": 10, "sex": "male"})
writer.writerow({"name": "lis", "age": 20, "sex": "male"})
with open('person.csv', 'r') as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
每行输出的是一个字典对象
OrderedDict([('name', 'zhangsan'), ('age', '10'), ('sex', 'male')])
OrderedDict([('name', 'lis'), ('age', '20'), ('sex', 'male')])
默认情况下导出的字符串全是数字时,在excel中打开时会被自动转换成科学计数格式
import csv
field_order = ["会诊单号"]
with open("导出.csv", 'w', encoding="utf8", newline="") as csvfile:
writer = csv.DictWriter(csvfile, field_order)
writer.writeheader()
writer.writerow({"会诊单号": "20210217162737860175"})
只需要在字符串后面加转义字符’\t’即可变成字符串
import csv
field_order = ["会诊单号"]
with open("导出.csv", 'w', encoding="utf8", newline="") as csvfile:
writer = csv.DictWriter(csvfile, field_order)
writer.writeheader()
writer.writerow({"会诊单号": "20210217162737860175"+'\t'})
评论