How can I lock a file in Windows?

Fredrik Lundh fredrik at pythonware.com
Sat Mar 9 11:15:22 EST 2002


A.Newby wrote:

> I am writing a cgi based, html chat script in Python. Basically, it takes
> input from people's browsers, writes it to a text file, then displays the
> contents of that file back to everyone. Simple.
>
> Problem is I need to be able to lock the text file during the write
> procedure, so that only one person can write to it at a time.
> Unfortunately, not having access to a Unix server atm, I'm using Windows.
> That means I don't have the fcntl module, which means I can't use flock to
> lock the file.
>
> Is there another way I can lock the file in Windows?

did you look under "MS Windows Specific Services" in the
library reference?

http://www.python.org/doc/current/lib/module-msvcrt.html
=> "file operations"

something like this should work:

def update(filename, new_content):
    file = open(filename, "r+")
    # look from current position (0) to end of file
    msvcrt.locking(file.fileno(), msvcrt.LK_LOCK, os.path.getsize(filename))
    file.seek(0)
    file.write(new_content)
    file.close() # unlocks the file

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list