簡體   English   中英

Python-執行順序(文件讀寫)

[英]Python - execution order (file writing and reading)

請問有什么理由

out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close
system('gnuplot -persist tmp.gp')

不起作用,但是這些(下面)可以嗎?

system('gnuplot -persist tmp.gp')
out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close

請注意,我不會在程序執行期間刪除tmp.gp,因此無論哪種情況,文件都存在並且在執行任何這些行之前都包含命令'plot sin(x)'(因為該文件存在於上一次運行中)?

我唯一的猜測是,這可能是競爭條件,但是放置raw_input()來消磨時間並沒有幫助(請參閱下文)。 謝謝你的幫助!

out = open("tmp.gp",'w')
out.write('plot sin(x)')
out.close
raw_input()
system('gnuplot -persist tmp.gp')

這是因為您實際上並未調用close函數, out.closeout.close()更改為out.close() 函數調用require ()才能被調用。

正如其他人提到的那樣,您沒有正確使用close()。 同樣,在處理文件時,應使用語句:

with open("tmp.gp",'w') as out:
    out.write('plot sin(x)')
    out.close()

這樣,即使您自己不會關閉文件或寫入文件也會引發錯誤,文件仍然會關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM