更新时间:2023-11-18 22:08:16
你想要做什么:
>>> 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
一次性写入。如果你的文件是非常,非常大这如这篇文章的注释所示,请注意,不是
嵌套两个和
语句,你可以在同一个行:
lineterminator
parameter in csv.writer
. By default it is
set to '\r\n'
and this is why you have double spacing.writerows
. If your file is very, very big this
probably is not a good idea (RAM) but for normal files I think it is
faster because there is less I/O.As indicated in the comments to this post, note that instead of
nesting 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: