Python CSV 模块的用法

unsplash

python csv module的用法。

读取csv文件的代码

1
2
3
4
5
6
7
8
9
10
11
12
import csv

def csv_reader(file_obj):
"""Read a csv file"""
reader = csv.reader(file_obj)
for row in reader:
print(" ".join(row))

if __name__ == '__main__':
csv_path = 'filename.csv'
with open(csv_path, 'r') as file_obj:
csv_reader(file_obj)

使用DictReader读取csv文件

1
2
3
4
5
6
7
8
9
10
11
import csv

def csv_dict_reader(file_obj):
"""Read a CSV file using csv.DictReader"""
reader = csv_DictReader(file_obj, delimeter=',')
for line in reader:
print(line['colume-name'])

if __name__ == '__main__':
with open('filename.csv') as file_obj:
csv_dict_reader(file_obj)

写入CSV文件

1
2
3
4
5
6
7
8
9
10
11
import csv

def csv_writer(data, path):
with open(path, 'w', newline='') as csv_file:
for line in data:
writer.writerow(line)

if __name__ == '__main__':
data = ['first_name', 'last_name', 'city'.split(','), ...]
path = 'output.csv'
csv_writer(data, path)

用DictWriter写入CSV文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import csv

def csv_dict_writer(path, field_names, data):
"""Write a CSV file using DictWriter"""
with open(paht, 'w', newline='') as out_file:
writer = csv.DictWriter(out_file, delimeter=',', field_names=filenames)
writer.writeheader()
for row in data:
writer.writerow(row)

if __name__ == '__main__':
data = ['first_name', 'last_name', 'city'.split(','), ...]
my_list = []
field_names = data[0]
for values in data[1:]:
inner_dict = dict(zip(field_names, values))
my_list.append(inner_dict)

path = 'dict_output.csv'
csv_dict_writer(path, field_names, my_list)
0%