Search code examples
pythonfile-ioraspbianpython-3.5

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


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

This related question suggests 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?

Thanks for the help!


Solution

  • You should open the same file but assign them to different variables, like so:

    file_obj = open(filename, "wb+")
    
    if not file_obj.closed:
        print("File is already opened")
    

    The .closed only checks if the file has been opened by the same Python process.