[Tutor] locking files

Alan Gauld alan.gauld at btinternet.com
Wed Jun 13 18:23:26 CEST 2007

"Jeff Peery" <jeffpeery at yahoo.com> wrote

> does anyone know if there is a way in python to lock 
> a file so others cannot open it, or can only read it? 

Thats normally controlled by your OS and the rules vary 
slightly between them. In general if you open a file for 
writing the OS should lock it against writing (and in 
some cases against reading too!). So if you want to 
lock an existing file while you read and write you could use 
a mode string of 'r+'. If you want to create a new locked 
file use 'w+''. BUT remember that its up to you to manage 
where the cursor is, otherwise you could wind up overwriting 
your data.

Another way to protect access, but less reliable, is 
to change the file permissions (using os.chmod()) 
at the start of the operation and change themback at 
the end. But that will only protect ahainst access by 
other users not against access by other programs that 
you might be running! Also you need to have 
permission to change permissions in the first place!


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list