我正在嘗試編寫一個讀取一個csv文件的程序,然後根據輸入文件創建兩個不同的輸出文件。Python:用於創建和寫入兩個輸出文件的函數
file = open("file.csv","r")
def createFile(data_set):
output0 = open("Output" + data_set + ".txt","w")
print >> output0, 'h1,h2,h3,h4'
return output0
def runCalculations(data_set, output):
for row in file:
# equations and stuff
if data_set == 1:
print >> output, row[1]+','+row[2]+','+row[3]+','+x
if data_set == 2:
print >> output, row[4]+','+row[5]+','+row[6]+','+y
output.close()
output1 = createFile(1)
runCalculations(1, output1)
output2 = createFile(2)
runCalculations(2, output2)
file.close()
Output1是完美的,格式化,一切都完全如此。對於Output2,文件被創建,並且列的標題是可見的(所以'createFile'工作正常),但'runCalculations'功能從不運行,包括方程式(我通過在這裏和那裏放置幾個打印函數)
沒有錯誤消息,我試着在每個函數和參數中更改輸出文件的變量名稱(以前所有內容都只是「輸出」)。我也嘗試在'runCalculations'方法之外單獨關閉每個文件(output1和output2)。我錯過了什麼是阻止'runCalculations'函數被第二次調用?
對不起,如果解決方案是非常明顯的,我一直在這個工作一段時間,所以新鮮的眼睛是一個很大的幫助。非常感謝您的寶貴時間!
(0)'前加''output.seek爲行中的文件:''中runCalculations'。 –