2015-09-10 143 views
0

我有這個問題。我讓這個功能在csv文件上做了一些修復。它只在我第一次打電話時有效,但不是第二次。 感謝您的幫助!我正在調用一個函數兩次,但它只在第一次運行

import csv 

file = open('original.csv', 'r') 
fileOut = open('fixed.csv', 'wb') 

# Make a list out of the csv content 
read = [x for x in csv.reader(file)] 
writer = csv.writer(fileOut, delimiter=',', quoting=csv.QUOTE_NONE) 

# Function to make changes to the csv 
def rep(field, uno, dos): 
    for x in read: 
     x[field] = x[field].replace(uno, dos) 
     writer.writerow(x) 

# First call 
rep(0, 'COMISARIA ', '') 

# Second call 
rep(4, 'AVDA', '') 

fileOut.close() 
+0

多少行沒有原始CSV有,又有多少行貴固定CSV有哪些? – Kevin

+1

你看到的問題到底是什麼?什麼是投入,實際產出和預期產出? – interjay

+0

您是否記得.close()您的輸入文件? – Symmitchry

回答

1

問題出在你撥打writer的地方。當你第一次打電話時,它會把所有的輸出放到'fixed.csv'。然後,第二次調用func時,它將行添加到該文件的末尾。

的解決方案是不調用repwriter.writerow(x),而是做:

# Second call 
rep(4, 'AVDA', '') 

writer.writerows(read) 
fileOut.close() 
+1

完美的工作,謝謝很多人。 – Ivan

+0

你懂了,編程好運。 – acushner

相關問題