这是纠正错误的代码:
import csv
from itertools import izip_longest
# Creating a CSV file
with open(r'Data.csv','wb') as f:
fw = csv.writer(f)
fw.writerows( (('Heading 1', 'Heading 2'),
('1'),
('1'),
('0'),
('2'),
('1'),
('0')) )
print "The CSV file at start, read by a csv.reader :\n"
with open(r'Data.csv','rb') as f:
fr = csv.reader(f)
print '\n'.join(map(repr,fr))
print '\n------------------------------------------'
newdata = [10,0,10,20,10,20,10,10]
with open(r'Data.csv','rb') as f:
fr = csv.reader(f)
newrows = [fr.next()]
newrows += (a+[b] for a,b in izip_longest(fr, newdata,
fillvalue=[0]))
print 'newrows\n',newrows
with open(r'Data.csv', 'wb') as f:
csv.writer(f).writerows(newrows)
print '------------------------------------------\n'
print "The new CSV file created, read by a csv.reader :\n"
with open(r'Data.csv','rb') as f:
fr = csv.reader(f)
print '\n'.join(map(repr,fr))
它显示:
The CSV file at start, read by a csv.reader :
['Heading 1', 'Heading 2']
['1']
['1']
['0']
['2']
['1']
['0']
------------------------------------------
newrows
[['Heading 1', 'Heading 2'], ['1', 10], ['1', 0], ['0', 10], ['2', 20], ['1', 10], ['0', 20], [0, 10], [0, 10]]
------------------------------------------
The new CSV file created, read by a csv.reader :
['Heading 1', 'Heading 2']
['1', '10']
['1', '0']
['0', '10']
['2', '20']
['1', '10']
['0', '20']
['0', '10']
['0', '10']
编辑
更加凝练
import csv
from itertools import izip_longest
from os import remove,rename
# Creating a CSV file
with open(r'Data.csv','wb') as f:
fw = csv.writer(f)
fw.writerows( (('Heading 1', 'Heading 2'),
('1'),
('1'),
('0'),
('2'),
('1'),
('0')) )
print "The CSV file at start, read by a csv.reader :\n"
with open(r'Data.csv','rb') as f:
print '\n'.join(map(repr,csv.reader(f)))
#------------------------------------------
newdata = [10,0,10,20,10,20,10,10]
with open(r'Data.csv','rb') as f, open(r'newData.csv','wb') as g:
fr = csv.reader(f)
gw = csv.writer(g)
gw.writerow(fr.next())
gw.writerows( a+[b] for a,b in izip_longest(fr, newdata,
fillvalue=[0]) )
remove (r'Data.csv')
rename (r'newData.csv',r'Data.csv')
#------------------------------------------
print "The new CSV file created, read by a csv.reader :\n"
with open(r'Data.csv','rb') as f:
print '\n'.join(map(repr,csv.reader(f)))