csv - 如何使用 python 将新列添加到CSV文件中?

我有几个CSV文件,看起来像这样:


Input 
Name Code 
blackberry 1 
wineberry 2 
rasberry 1 
blueberry 1 
mulberry 2

我想为所有CSV文件添加一个新列,这样它看起来就像这样:


Output 
Name Code Berry 
blackberry 1 blackberry 
wineberry 2 wineberry 
rasberry 1 rasberry 
blueberry 1 blueberry 
mulberry 2 mulberry 

我目前的脚本是:


import csv
with open(input.csv,'r') as csvinput:
 with open(output.csv, 'w') as csvoutput:
 writer = csv.writer(csvoutput)
 for row in csv.reader(csvinput):
 writer.writerow(row+['Berry'])

(python 3.2 )

但是,在输出中,脚本会跳过每一行,新列中只包含Berry:


Output 
Name Code Berry 
blackberry 1 Berry 

wineberry 2 Berry 

rasberry 1 Berry 

blueberry 1 Berry 

mulberry 2 Berry 

时间:

这应该可以让你知道该怎么做:


>>> v = open('C:/test/test.csv')
>>> r = csv.reader(v)
>>> row0 = r.next()
>>> row0.append('berry')
>>> print row0
['Name', 'Code', 'berry']
>>> for item in r:
... item.append(item[0])
... print item
... 
['blackberry', '1', 'blackberry']
['wineberry', '2', 'wineberry']
['rasberry', '1', 'rasberry']
['blueberry', '1', 'blueberry']
['mulberry', '2', 'mulberry']
>>> 

在py3k中你必须使用next(r)

给你有一个额外的(可工作的脚本):


import csv

with open('C:/test/test.csv','r') as csvinput:
 with open('C:/test/output.csv', 'w') as csvoutput:
 writer = csv.writer(csvoutput, lineterminator='n')
 reader = csv.reader(csvinput)

 all = []
 row = next(reader)
 row.append('Berry')
 all.append(row)

 for row in reader:
 row.append(row[0])
 all.append(row)

 writer.writerows(all)

请注意

  1. csv.writer中的lineterminator参数,默认情况下,它设置为'rn',这就是为什么你有双间距,
  2. 使用列表追加所有行,并且将它写入writerows中的一次快照,如果你的文件非常大,这可能不是一个好主意,但是,对于普通文件,我认为它更快。

import csv
with open('input.csv','r') as csvinput:
 with open('output.csv', 'w') as csvoutput:
 writer = csv.writer(csvoutput)

 for row in csv.reader(csvinput):
 if row[0] == "Name":
 writer.writerow(row+["Berry"])
 else:
 writer.writerow(row+[row[0]])

也许是你想要的东西?

另外,csv使用逗号分隔值,因此,你需要使用逗号来分隔你的值,我认为:


Name,Code
blackberry,1
wineberry,2
rasberry,1
blueberry,1
mulberry,2

我不了解你添加新列的位置,但是请尝试:


 import csv
 i = 0
 Berry = open("newcolumn.csv","r").readlines()
 with open(input.csv,'r') as csvinput:
 with open(output.csv, 'w') as csvoutput:
 writer = csv.writer(csvoutput)
 for row in csv.reader(csvinput):
 writer.writerow(row+","+Berry[i])
 i++


while running the below program getting error

import csv
i = 0
Berry = open("D:PythonInputnewcolumn.csv","r").readlines()

with open("D:PythonInputinput.csv",'r') as csvinput:
 with open("D:PythonInputoutput.csv",'w') as csvoutput:
 writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
 writer.writerow(row+","+Berry[i])
 i+=1

i am using Python 3.3

...