Python Forum

Full Version: Keep a file locked for the life of an application
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Suppose I have a file I'm reading from and I want to keep it open for the life of the application, until the users quits. Using Python under Windows, is it possible?

Essentially what i want to do is what any word processor does, once a file is open in the word processor, it's locked as long as the word processor is open, and if you attempt to delete/move it, the OS will generate an error usually along the lines of "This file cannot be removed, it's being used by (program name here)"
def foo():
    pass

def bar():
    pass
if __name__ == "__main__":
    f = open('file.txt')

    # do something
   
    sys.exit(f.close())
For instance...
On not-windows, you have the fcntl module which can lock files (or parts of files): https://docs.python.org/3/library/fcntl....cntl.flock
On windows, the same functionality can be found in the msvcrt module: https://docs.python.org/3.6/library/msvc...rt.locking