Python-错误-AttributeError:“ _ io.TextIOWrapper”对象没有属性“插入”

时间:2018-08-30 18:11:06

标签: python python-3.x

我正在尝试在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

1 个答案:

答案 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)