[Tutor] Atomic file creation?

Wesley Brooks wesbrooks at gmail.com
Fri Sep 28 11:27:58 CEST 2007


Dear Users,

I'm looking for an atomic method for creating a file on the hard disk
from python.

Currently I'm using;

def (command):
    """Creates a file with the name given by command."""
    comFile = open(comFileName, 'w')
    comFile.close()

This is not atomic as there are two operations needed to create this
file. If the process was disturbed between these two files another
process may not be able to read and delete the file (just reading the
file name) as the above process may still hold it open.

I realise I could do:

import os

def (command, tempDir='tempFiles', targetDir='commandDirectory'):
    """Creates a file with the name given by command in a temporary
    directory then moves it over to a target directory."""
    tempName = os.path.join(tempDir,comFileName)
    finalName = os.path.join(targetDir,comFileName)
    comFile = open(tempName, 'w')
    comFile.close()
    os.rename(tempName, finalName)

This is now atomic as far as anything watching targetDir is concerned.
In other words as soon as it can be seen in the directory it is safe
to be read and destroyed with out having to worry about another
process not having closed the file for what ever reason.

I do have two problems with this though;

1. This may fail under windows if another file already exists with
this file name in the target directory. I always try to get my code
working on Linux and windows, this leaves my code more robust and
interestingly sometimes the Linux interpreter picks up different
errors than the windows interpreter and visa versa.

2. It doesn't look very nice! I'm assuming there must be something in
python to create a and release a file on the system in one line of
code?

Thank in advance of any help.

Cheers,

Wesley Brooks.


More information about the Tutor mailing list