python csv lib


Author: yifei / Created: May 29, 2017, 10:14 p.m. / Modified: May 29, 2017, 10:18 p.m. / Edit

typical usage

注意dictwriter需要提供fieldnames

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

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

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

评论区