我正在尝试在csv文件中插入一列,并将该列增加一。 我在主题中遇到了以上错误:
with open('C:\\temp\\XXX\\names.csv','r') as rf:
with open('C:\\temp\\XXX\\Testcopyx.csv','w') as wf:
for line in rf:
wf.write(line)
wf.insert(0, 'New_ID', range(0, 0 + len(wf)))
# wf
wf.close
答案 0 :(得分:0)
下面,我使用csv
模块将一个csv文件从一个文件转录到另一个文件,并在末尾添加一列,该列随行而递增
import csv
infile = 'C:\\temp\\XXX\\names.csv'
outfile = 'C:\\temp\\XXX\\Testcopyx.csv'
with open(infile, newline='') as rf, open(outfile, 'w+', newline='') as wf:
reader = csv.DictReader(rf)
writer = csv.DictWriter(wf, [*reader.fieldnames, "New ID"]) # Add the new column name
writer.writeheader()
for count, row in enumerate(reader):
row.update({"New ID": count}) # update the row to have the new column
writer.writerow(row)