Python CSV 模块读取及写入 CSV 文件

本文最后更新于:2020-09-10 20:38

Python CSV 模块读取及写入 CSV 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 读取CSV文件的第一行设定为 header
def get_csvheader(filename):
for line in open(filename + '.csv', encoding = 'utf-8', errors = 'ignore'):
return line.split(',')

# 读取 csv 文件到字典中
def read_csvfile_to_dict(filename):
header = get_csvheader(filename)
thedict = {}
with open(filename + '.csv') as f:
reader = csv.DictReader(f)
for row in reader:
rowdata = {}
for item in header:
rowdata[item] = row[item]
thedict[len(thedict)] = rowdata
return thedict

# 把字典写入 csv 文件中的一行
def save_dict_to_csvfile(dict_to_write, filename):
header = get_csvheader(filename)
with open(filename + '.csv', 'a', encoding = 'gbk', errors = 'ignore', newline = '') as f:
writer = csv.DictWriter(f, header)
writer.writerow(dict_to_write)