且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中的csv文件中添加一个新列

更新时间:2023-11-18 22:47:46

没有输入要测试,但试试这个。您当前的方法不包括输入数据中已存在的每行的现有数据。 extend 将接受代表每一行的列表,然后向该列表添加另一个项...等效于添加列。

No input to test, but try this. Your current approach doesn't include the existing data for each row that already exists in your input data. extend will take the list that represents each row and then add another item to that list... equivalent to adding a column.

import CSV
with open(filename) as csvin:
    readfile = csv.reader(csvin, delimiter=',')
    with open(output, 'w') as csvout:
        writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
        for row in readfile:
            row.extend([str(row[10]) + ' ' + str(row[11])])
            writefile.writerow(row)