如何检查文件是否已打开(在同一过程中)

时间:2016-05-29 22:28:45

标签: python file-io raspbian python-3.5

我想通过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

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

您打开相同的文件,但将它们分配给不同的变量。你应该做的是:

fileobj=open(filename,"wb+")

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

我正在用手机写字,所以造型可能不太好,但你会明白这一点。顺便说一句,.closed只检查文件是否已被同一个python进程打开。

答案 1 :(得分: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