可能最簡單的解決方案是使用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
比較這對爲同一目的(從here修改)的CSV模塊代碼:
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)
你只有一個頭字段。你如何期望它創建多個列? – ozgur
文件中有現有的列,我想將'Score'和數組'score []'一起追加到文件中。 –
通常,您必須讀取現有文件,逐行添加新列,並將結果行寫入新文件。 –