2016-05-29 35 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

相关问题