This question already has answers here:
add a new column to an existing csv file

(4个答案)


5年前关闭。




我在数组中存储了一组四个数字,我想将它们添加到“得分”列下的CSV文件中。
with open('Player.csv', 'ab') as csvfile:
    fieldnames = ['Score']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    for i in range(0, l):
       writer.writerow({'Score': score[i]})

它追加到文件中,但是会添加一个新行,而不是一个新列。有人可以指导将其附加到新列中吗?

最佳答案

可能最简单的解决方案是使用Pandas。这是过大的,但是对于CSV操作而言,它通常要干净得多,而CSV操作超出了直接读取/写入的范围。

假设我有一个CSV文件,如下所示:

ASSETNUM    ASSETTAG    ASSETTYPE   AUTOWOGEN
cent45  9164        0
cent45  9164        0

然后,用于添加列的相关代码如下:
import pandas as pd

df = pd.read_csv('path/to/csv.csv', delimiter='\t')
# this line creates a new column, which is a Pandas series.
new_column = df['AUTOWOGEN'] + 1
# we then add the series to the dataframe, which holds our parsed CSV file
df['NewColumn'] = new_column
# save the dataframe to CSV
df.to_csv('path/to/file.csv', sep='\t')

这将添加一个新列,可很好地缩放,并且易于使用。生成的CSV文件将如下所示:
    ASSETNUM    ASSETTAG    ASSETTYPE   AUTOWOGEN   NewColumn
0   cent45  9164        0   1
1   cent45  9164        0   1

出于相同目的将其与CSV模块代码进行比较(从here修改):
with open('path/to/csv.csv', 'r') as fin:
    reader = csv.reader(fin, delimiter='\t')
    with open('new_'+csvfile, 'w') as fout:
        writer = csv.writer(fout, delimiter='\t')
        # set headers here, grabbing headers from reader first
        writer.writerow(next(reader) + ['NewColumn']

        for row in reader:
            # use whatever index for the value, or however you want to construct your new value
            new_value = reader[-1] + 1
            row.append(new_value)
            writer.writerow(row)

关于python - 如何使用Python将新列附加到CSV文件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36882130/

10-12 00:16
查看更多