2016-05-29 53 views
6

我想用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

感謝您的幫助!

+0

我可以打開一個文件多次的原因是因爲「僅適用於Windows鎖定的文件打開時寫作。POSIX平臺不支持。」有關更多信息,請參閱http://stackoverflow.com/questions/22617452/opening-already-opened-file-does-not-raise-exception。 – maximedupre

+0

如果你在同一個進程中運行,你會如何知道文件是否打開? –

+0

@PadraicCunningham我有一個腳本,用於導入可以打開和關閉文件的外部庫/模塊。我的腳本需要知道該文件當前是打開還是關閉的方法。 – maximedupre

回答

4

您打開相同的文件,但將它們分配給不同的變量。你應該做的是:

fileobj=open(filename,"wb+") 

if not fileobj.closed: 
    print("file is already opened")` 

我正在用我的手機寫,所以造型可能不好,但你會明白的。順便說一下,.closed只檢查文件是否已被相同的python進程打開。

+0

這不解決OP的問題?他在詢問如何檢查特定文件是否打開。 'f = open(f_name,mode)!= f_o = open(f_name,mode)'因爲open()返回某個fileobj的實例。因此,假設你在前一行打開文件,'fileobj.closed'總是會計算爲'False'? – TheLazyScripter

+0

儘管這種技術不夠靈活,並且不使用try ... except構造,但它不依賴於平臺,並且實際上可行。我不知道爲什麼它被降低了。 – maximedupre

2

我會建議使用這樣的東西。

def is_open(file_name): 
    if os.path.exists(file_name): 
     try: 
      os.rename(file_name, file_name) #can't rename an open file so an error will be thrown 
      return False 
     except: 
      return True 
    raise NameError 

編輯以適應OP的具體問題

class FileObject(object): 
    def __init__(self, file_name): 
     self.file_name = file_name 
     self.__file = None 
     self.__locked = False 

    @property 
    def file(self): 
     return self.__file 

    @property 
    def locked(self): 
     return self.__locked 

    def open(self, mode, lock=True):#any testing on file should go before the if statement such as os.path.exists() 
     #replace mode with *args if you want to pass multiple modes 
     if not self.locked: 
      self.__locked = lock 
      self.__file = open(self.file_name, mode) 
      return self.file 
     else: 
      print 'Cannot open file because it has an exclusive lock placed on it' 
      return None #do whatever you want to do if the file is already open here 

    def close(self): 
     if self.file != None: 
      self.__file.close() 
      self.__file = None 
      self.__locked = False 

    def unlock(self): 
     if self.file != None: 
      self.__locked = False 
+0

它不起作用,即使打開文件,我也可以「重命名」文件。也許是因爲我的操作系統是Raspbian? – maximedupre

+0

您可以在文件已被打開時重新命名文件。 –

+0

也許這個鎖是操作系統特定的,如果是這樣的話,我會看看這裏的Python開放模式http://www.tutorialspoint.com/python/os_open.htm並嘗試'os.O_CREAT'和'os.O_EXLOCK '或者組合。讓我知道這是否適用於Raspbian。我認爲它會因爲它不是特定的。 – TheLazyScripter

相關問題