如何使用Python将新列附加到CSV文件?

时间:2016-04-27 06:36:50

标签: python csv

我已将一组四个数字存储在一个数组中,我想将其添加到“得分”列下的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]})

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

1 个答案:

答案 0 :(得分:1)

可能最简单的解决方案是使用Pandas。这样做太过分了,但对于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)