safe simultaneous file append?

Dale Strickland-Clark dale at
Mon Oct 8 10:46:52 CEST 2001

Graham Guttocks <graham_guttocks at> wrote:

>Given the following code, is there any danger of the logfile being
>corrupted if two copies of this code try to append at the same time?
>  file = open('logfile.txt','a+')
>  file.write('testing' + '\n')
>  file.close()
>If so, how do I guard against this?  This is on UNIX BTW.

Yes. You can't append to a file from two different places at once. You
have a few choices:

1. A log daemon. You tell it it write a record (using a named pipe, or
similar approach) and it looks after the file.
2. A log routine that locks the file during write. If it's already
locked, wait until the lock is released.
3. A log directory. Each process uses its own randomly named file but
use time-stamped records. Sort/merge it all at the end of a day (or

There are probably others.
Dale Strickland-Clark
Riverhall Systems Ltd

More information about the Python-list mailing list