各位大大好,請先看一段小小程式碼,如下:
for x in range(1,1001,1):
with open('fix.csv','rb') as csvinput:
with open('fix_append.csv','wb') as csvoutput:
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
if j<len(AddNewColumn):
writer.writerow([row[0],row[1],...,row[x],AddNewColumn[j]])
以上就是想把fix.csv的東西寫進fix_append.csv,然後再加上一列AddNewColumn的值
以下為小弟問題,請問各位大大
如何將writer.writerow([row[0],row[1],...,row[x],AddNewColumn[j]])的row[x]設定
為變數呢?
也就是說,在最上層的for迴圈裡,
當x=1,writer.writerow([row[0],AddNewColumn[j]])
當x=2,writer.writerow([row[0],row[1],AddNewColumn[j]])
當x=3,writer.writerow([row[0],row[1],row[3],AddNewColumn[j]])
小弟有嘗試用字串的方式來解,如下
for x in range(1,1001,1):
xxx="%d"%(x-1)
RowString=RowString+'row['+xxx+'],'
with open('fix.csv','rb') as csvinput:
with open('fix_append.csv','wb') as csvoutput:
writer = csv.writer(csvoutput)
for row in csv.reader(csvinput):
if j<len(AddNewColumn):
Astring= RowString + "AddNewColumn["+ "%d"%j +"]"
Astring=Astring.split(',')
writer.writerow(Astring)
用上述方式印在fix_append.csv表上的就不是fix.csv裡每一行row的值了,而是單純的字
串row[0]、...、row[x]、AddNewColumn[j]
麻煩各位程式大神解惑了,感謝!