我有一个像这样的csv文件:
A,Film, Yes
B,Grass,No
C,Bottle,No
D,Love,Yes
E,Red,No
我的系统列表是这样的:
['No','No','Yes','Yes','No']
如何将列表添加到新列中,我的期望是这样的:
A,Film, Yes,No
B,Grass,No,No
C,Bottle,No,Yes
D,Love,Yes,Yes
E,Red,No,No
我该怎么做?
答案 0 :(得分:0)
使用CSV模块。
<强>演示:强>
import csv
toAdd = ['No','No','Yes','Yes','No']
with open(filename, "r") as infile:
data = [i.strip().split(",") for i in infile.readlines()]
with open(filename, "w") as outfile:
writer = csv.writer(outfile, delimiter=",")
for i, value in enumerate(toAdd, 0):
v = data[i]
v.extend([toAdd[i]])
writer.writerow(v)
答案 1 :(得分:0)
您可以使用zip
:
import csv
with open('filename.csv') as f:
with open('filename.csv', 'w') as f1:
headers = ['No','No','Yes','Yes','No']
data = list(csv.reader(f))
write = csv.writer(f1)
write.writerows([a+[b] for a, b in zip(data, headers)])
答案 2 :(得分:0)
对于更复杂的操作,应考虑csv模块。但是,要仅将简单列表的内容添加为文件的最后一列,简单的字符串处理应该足够了:
lastcol = ['No','No','Yes','Yes','No']
with open(infile) as fdin, open(outfile, "w") as fdout:
for i, line in enumerate(fdin):
print(line.rstrip(), lastcol[i], sep=",", file=fdout)
上面假设列表至少和文件一样长......
答案 3 :(得分:-1)
如果您想使用pandas
库,可以执行以下操作:
import pandas as pd
list = ['No','No','Yes','Yes','No']
df = pd.read_csv('data.csv')
df['new_column'] = list
df.to_csv('modified_data.csv')