$ ls ~yifei/notes/

Python 读写 CSV 文件

Posted on:

Last modified:

注意 dictwriter 需要提供 fieldnames

with open("file.csv", "wt", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=[], extrasaction="ignore")
    writer.writeheader()
    writer.writerow(d)  # list of dict if using writerows

with open("file.csv", "wt", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(l)  # list of list if using writerows

with open("file.csv", "rt") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

另一种更好的方法是使用 pandas

WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站