Python Forum
Keep a file locked for the life of an application - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Keep a file locked for the life of an application (/thread-5389.html)



Keep a file locked for the life of an application - rachelrosemond - Oct-01-2017

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)"


RE: Keep a file locked for the life of an application - wavic - Oct-01-2017

def foo():
    pass

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

    # do something
   
    sys.exit(f.close())
For instance...


RE: Keep a file locked for the life of an application - nilamo - Oct-03-2017

On not-windows, you have the fcntl module which can lock files (or parts of files): https://docs.python.org/3/library/fcntl.html#fcntl.flock
On windows, the same functionality can be found in the msvcrt module: https://docs.python.org/3.6/library/msvcrt.html#msvcrt.locking