问题描述
我有几个文件,如下所示:
I have several CSV files that look like this:
Input
Name Code
blackberry 1
wineberry 2
rasberry 1
blueberry 1
mulberry 2
我想为所有CSV文件添加一个新列,如下所示: / p>
I would like to add a new column to all CSV files so that it would look like this:
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)
(Python 3.2)
但是在输出中,脚本跳过每一行,新列只有Berry。
But in the output, the script skips every line and the new column has only Berry in it:
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)
Edit, note in py3k you must use next(r)
感谢您接受答案。这里有一个奖励(你的工作脚本):
Thanks for accepting the answer. Here you have a bonus (your working script):
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)
p>
Please note
-
中的
。默认情况下,lineterminator
参数csv.writer
设置为'\r\\\
,这就是为什么你有双倍间距。
' - 使用列表来附加所有行,并在
中用writerows
一次性写入。如果你的文件是非常,非常大这
可能不是一个好主意(RAM),但对于正常文件,我认为它是
更快,因为有更少的I / O。 -
如这篇文章的注释所示,请注意,不是
嵌套两个和
语句,你可以在同一个行:
- the
lineterminator
parameter incsv.writer
. By default it isset to'\r\n'
and this is why you have double spacing. - the use of a list to append all the lines and to write them inone shot with
writerows
. If your file is very, very big thisprobably is not a good idea (RAM) but for normal files I think it isfaster because there is less I/O. As indicated in the comments to this post, note that instead ofnesting the two
with
statements, you can do it in the same line:
打开('C:/test/test.csv','r')as csvinput,open('C:/test/output.csv' ,'w')as csvoutput:
with open('C:/test/test.csv','r') as csvinput, open('C:/test/output.csv', 'w') as csvoutput:
这篇关于如何使用Python向CSV文件中添加新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!