2016-07-15 55 views
0

寫入文件時出現問題。 似乎發生的情況是程序以0,1,2,3的順序打印數字(第零,第一,第二,第三),但以-1,0,1,2的順序寫入文件。即使在print to screen命令在寫入文件命令之後執行。 示例代碼如下。任何想法如何使它寫入文件的順序0,1,2,3?寫入文件並打印到彼此不同步屏幕

非常感謝 - Scriptham。

import random 
import time 

ln = 4 
mins = 10 
j = 0 
n_sensor = 0 
temp_c = 0 
data_file = "/home/pi/laboratory/test.csv" 

def read_temp(): 
    temp_c = 100 * random.random() 
    return str("%.3f"% temp_c) 


for j in range (1,mins): 
    f = open(data_file,'a') 
    f.write("\n" + str(j)) 
    f.close 
    for n_sensor in range (0,ln): 
     #device_file_1 = 
     print("A " + str(n_sensor)) 
     x = read_temp() 
     f = open(data_file, 'a') 
     f.write("," + x) 
     f.close 
     print("OP temp_c = ", x) 
     #time.sleep(0.5) 
    time.sleep(10) #normally would be 59.5 or 60 or similar 

quit() 

回答

1

爲確保文件始終處於關閉狀態,應使用with語句。 例如:

with open(data_file, 'a') as f: 
    f.write("\n" + str(j)) 

這將關閉該文件,即使write期間發生異常。

或者,你需要使用類似:

f = open(data_file, 'a') 
try: 
    f.write("\n" + str(j)) 
finally: 
    f.close() 
+0

三江源這對你的意見,該方案現在可以正常工作。問題解決了。 ScriptHam – scriptham

+0

如果您的問題已得到解答,請將其中一個解決方案標記爲正確。 –

+0

謝謝skyhisi。我不確定如何標記事情是正確的。有關信息的兩部分都用於解決問題。 – scriptham

4

問題很可能是您打開輸出文件幾十次,但從不關閉它。

你應該循環只有一次f = open(data_file,'a')。然後當一切都完成後,致電f.close()f.close不等於f.close()!)。