我想用try catch構造來具體實現。如何檢查一個文件是否已經打開(在同一個進程中)
這related question表明,我可以這樣做:
try:
open(fileName, 'wb+')
except:
print("File already opened!")
raise
但是,這是行不通的我。我可以多次打開同一個文件,沒有任何問題:
fileObj1 = open(fileName, 'wb+')
fileObj2 = open(fileName, 'wb+')
是因爲我有Python 3.5嗎?或因爲我使用Raspbian?
感謝您的幫助!
我可以打開一個文件多次的原因是因爲「僅適用於Windows鎖定的文件打開時寫作。POSIX平臺不支持。」有關更多信息,請參閱http://stackoverflow.com/questions/22617452/opening-already-opened-file-does-not-raise-exception。 – maximedupre
如果你在同一個進程中運行,你會如何知道文件是否打開? –
@PadraicCunningham我有一個腳本,用於導入可以打開和關閉文件的外部庫/模塊。我的腳本需要知道該文件當前是打開還是關閉的方法。 – maximedupre