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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37515574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:29:53  来源:igfitidea点击:

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

pythonfile-ioraspbianpython-3.5

提问by maximedupre

And I'd like to specifically achieve that with the try catch construct.

我想通过 try catch 构造专门实现这一点。

This related questionsuggests that I can do:

这个相关的问题表明我可以这样做:

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

However, it doesn't work me. I can open the same file multiple times without any problem:

但是,它对我不起作用。我可以多次打开同一个文件,没有任何问题:

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

Is it because I have Python 3.5? Or because I'm using Raspbian?

是因为我有 Python 3.5 吗?还是因为我使用的是Raspbian

Thanks for the help!

谢谢您的帮助!

采纳答案by atakanyenel

You open the same file but assign them to different variables. What you should do is:

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

fileobj=open(filename,"wb+")

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

I'm writing with my phone so the styling may not be good but you will get the point. By the way the .closedonly checks if the file has been opened by the same python process.

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

回答by TheLazyScripter

I would suggest using something like this

我建议使用这样的东西

# 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

Edited to fit the OP's specific issues

编辑以适应 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