参考大佬文章Python对csv文件的读写操作,感谢!
代码整理如下:
# coding=utf-8
import csv
"""
csv文件的写、读操作
"""
# -- 写入csv --
# 方式1(相对简洁)
# 如果为Python3.0需要在open()加入关键参数newline='',否则CSV文件将有两倍行距。
with open('file1.csv', 'w', newline='') as f:
head = ['name', 'sex', 'age']
infos = [
['LL', 'male', 28],
['HH', 'female', 26]
]
writer = csv.writer(f)
# 写入一行
writer.writerow(head)
# 写入多行
writer.writerows(infos)
# 方式2(字典型风格)
# 如果为Python3.0需要在open()加入关键参数newline='',否则CSV文件将有两倍行距。
with open('file2.csv', 'w', newline='') as g:
head2 = ['name', 'sex', 'age']
infos2 = [
{'name': 'LL', 'sex': 'male', 'age': 28},
{'name': 'HH', 'sex': 'female', 'age': 26}
]
writer = csv.DictWriter(g, head2)
writer.writeheader()
writer.writerows(infos2)
# -- 读取csv --
with open('file1.csv', 'r') as h:
reader = csv.reader(h)
for row in reader:
print(row) # 内容元素均为str类型