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

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

本文介绍了在python中的csv文件中添加一个新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向一个csv文件添加一个列,该列表合并了其他两列的字符串。每当我尝试这个我得到一个输出csv只有新的列或输出与所有的原始数据,而不是新的列。

I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column.

这是我到目前为止:

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 将接受代表每一行的列表,然后向该列表添加另一个项...等效于添加列。

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)

这篇关于在python中的csv文件中添加一个新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 07:09