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

How to check if a file is already opened (in the same process)

我想用 try catch 构造来具体实现这一点。

related question 建议我可以做:

try:
    open(fileName, 'wb+')
except:
    print("File already opened!")
    raise

然而,它对我不起作用。我可以毫无问题地多次打开同一个文件:

fileObj1 = open(fileName, 'wb+')
fileObj2 = open(fileName, 'wb+')

是不是因为我有Python3.5?或者因为我正在使用 Raspbian?

感谢您的帮助!

您应该打开同一个文件,但将它们分配给不同的变量,如下所示:

file_obj = open(filename, "wb+")

if not file_obj.closed:
    print("File is already opened")

.closed 仅检查文件是否已被相同的 Python 进程打开。

我建议使用这样的东西

# Only works on Windows
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