Exclusively lock a file to prevent other processes from reading it?

Philip Semanchuk philip at semanchuk.com
Tue May 4 17:46:29 EDT 2010


On May 4, 2010, at 5:37 PM, python at bdurham.com wrote:

> Is there a way to exclusively lock a file to prevent other
> processes from reading it while we have it open?
>
> I need to cache some overflow data to disk in a temp file and I
> want to make sure no other processes can read the contents of
> this file while I'm using it.
>
> I tried the following using an 'append binary' mode, but I can
> use NotePad to read the file while I'm using it:
>
> fd = open( r'a-temp-file.dat', 'ab' )
>
> My environment is Python 2.6.4 (32-bit) under Windows, but I'm
> looking for a cross-platform solution if that's possible.

Have a look at tempfile.mkstemp() in the standard library.






More information about the Python-list mailing list