Locking a file under Windows

Guy Lateur guy.lateur at b-b.be
Thu Nov 24 09:53:38 EST 2005


Hi all,

I'm working on an application that will be used by several users at the same 
time. The user should be able to both read and write to some data file 
stored on our file server. My question is: how can I prevent that one user 
writes to the file while another user is reading it?

I've seen some info on this in the fcntl module, but this module is not 
available under Windows, so I need something else. Here is what I've come up 
with so far:

def WriteToFile(filename):
    for i in range(max_nr_tries):
        try:
            fd = os.open(filename, os.O_EXCL | os.O_WRONLY)
        except OSError, (error, message):
            if error == errno.ENOENT:
                # create first
                try:
                    fd = os.open(filename, os.O_CREAT | os.O_EXCL | 
os.O_WRONLY)
                    break
                except:
                    print "Oops!"
            else:
                # try again later
                time.sleep(1)
                continue
    time.sleep(20)
    # + write & close file

I thought that, when this function gets to the last sleep(), I'd have an 
exclusive lock on the file. However, it seems I can still open the same file 
for reading/writing in another process (even os.O_EXCL).

Is this normal? What am I missing? How can I open a file exclusively (for 
writing)?

Thanks,
g





More information about the Python-list mailing list