0
在鏈接方法的情況下打開一個文件,如:關閉文件句柄與鏈接的方法
indata = open(from_file).read()
是否有必要(或可能)關閉文件當與open()
功能手柄打開?
如果不是,它不是做的最好做法:
infile = open(from_file)
indata = infile.read()
infile.close()
在鏈接方法的情況下打開一個文件,如:關閉文件句柄與鏈接的方法
indata = open(from_file).read()
是否有必要(或可能)關閉文件當與open()
功能手柄打開?
如果不是,它不是做的最好做法:
infile = open(from_file)
indata = infile.read()
infile.close()
在鏈式方法的情況下打開一個文件
時,這是鏈接方法的陷阱開文件,所以建議的解決方案是使用with clause
。對象的生命週期是with塊中,而它爲什麼是錯的FileObj文件被自動關閉
with open(from_file) as fin:
indata = fin.read()
?
其他代碼塊
infile = open(from_file)
indata = infile.read()
infile.close()
也有其缺陷。
感謝您的答覆。這很有意義。在這一點上,我避免了使用例外,因爲我正在通過學習Python艱難的方式進行工作,並且尚未在本書中達到這一點。我知道有很多打開文件可能會出錯,所以需要異常處理。 – joshschreuder 2013-03-01 05:34:50
關於「您處於GC關閉文件的擺佈」,那麼使用close()來顯式還是使用'with'語句是Python社區中的最佳實踐? – joshschreuder 2013-03-01 05:37:42
@shrodes:with語句不僅僅是更好,它是唯一的方法。 – Abhijit 2013-03-01 05:38:44