2016-03-03 28 views
1

我正在嘗試編寫一個讀取一個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

(0)'前加''output.seek爲行中的文件:''中runCalculations'。 –

回答

0

函數runCalculations耗盡數據文件。那就是問題所在。這將是測試打開該文件並關閉它在runCalculations。這也是更好地runCalculations創建輸出文件,請參見下面

def createFile(data_set): 
    output0 = open("Output" + data_set + ".txt","w") 
    print >> output0, 'h1,h2,h3,h4' 
    return output0 

def runCalculations(data_set, output): 
    file = open("file.csv","r") 
    output = createFile(data_set) 
    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() 
    file.close() 

runCalculations(1) 

runCalculations(2) 
+1

這很有道理,解決了這個問題。非常感謝你! – LNL

0

當您第一次執行runCalculations時,您將重複執行file對象,並且在循環結束後您將位於文件末尾。 這就是爲什麼第二次運行runCalculations時不計算計算的原因。你必須回到文件的開頭。

爲此,請在runCalculations函數的末尾添加file.seek(0)