python - 在 python 中向 csv 文件添加新列

标签 python python-2.7 csv

我正在尝试向 csv 文件添加一列,该文件组合了其他两列中的字符串。每当我尝试此操作时,我要么得到仅包含新列的输出 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:
            result = [str(row[10]) + ' ' + str(row[11])]
            writefile.writerow(result)

如有任何帮助,我们将不胜感激。

最佳答案

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

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)

关于python - 在 python 中向 csv 文件添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733158/

相关文章:

python - TensorFlow 数据集 API from_generator 序列结束错误

python-2.7 - mysql.connector,multi = True,sql变量赋值不起作用

python - 识别列表python中最不常见的数字

mysql - 如何从csv文件中获取数据并用mysql保存到grails中?

python - 如何仅将数据帧的列输出到文件

python - 以特殊条件连接 pandas 数据框

java - 删除 CSV 文件中的行

java - 将单记录 csv 文件读入类字段的编程习惯

python - 未知命令 : 'clearsessions'

Pythonanywhere - 错误代码 : Unhandled Exception