Python读取输出csv/tsv

Python读取或输出csv/tsv, 使用csv模块

读取

1
2
3
4
5
6
import csv
with open('in.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
...

读取tsv,csv.reader(f, delimiter='\t')

将数据读取到Dict中,以使用列名来访问:

1
2
3
4
5
import csv
with open('in.csv') as f:
f_csv = csv.DictReader(f)
for row in f_csv:
...

输出

1
2
3
out = csv.writer(sys.stdout)
out.writerow(header)
out.writerows(rows)

对于Dict数据:

1
2
3
out = csv.DictWriter(sys.stdout, fieldnames=header)
out.writeheader()
out.writerows(rows)

对于上面的fieldnames1

The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file.

其它方法

来自2

最后,如果你读取CSV数据的目的是做数据分析和统计的话, 你可能需要看一看Pandas包。
Pandas包含了一个非常方便的函数叫pandas.read_csv(),它可以加载CSV数据到一个DataFrame对象中去。

References

1. https://docs.python.org/3/library/csv.html
2. https://python3-cookbook-personal.readthedocs.io/zh_CN/latest/c06/p01_read_write_csv_data.html