python 操作 csv 文件
csv 文件的读取
import csv filename = '~/test/1.csv' with open(filename) as f: reader = csv.reader(f) # 读取一行,下面的reader中已经没有该行了 head_row = next(reader) for row in reader: # 行号从2开始 print(reader.line_num, row)
csv 文件的写入
import csv # 使用数字和字符串的数字都可以 datas = [['name', 'age'], ['Bob', 14], ['Tom', 23], ['Jerry', '18']] with open('example.csv', 'w', newline='') as f: writer = csv.writer(f) for row in datas: writer.writerow(row) # 还可以写入多行 writer.writerows(datas)