views:

319

answers:

1

I am using Python to write chunks of text to files in a single operation:

open(file, 'w').write(text)

If the script is interrupted so a file write does not complete I want to have no file rather than a partially complete file. Can this be done?

+8  A: 

I usually write to a temp file and when it has been successfully done, rename the file to the correct destination file e.g

f = open(tmpFile, 'w')
f.write(text)
f.close()

os.rename(tmpFile, myFile)

According to doc http://docs.python.org/library/os.html#os.rename

If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised even if it is a file; there may be no way to implement an atomic rename when dst names an existing file

Anurag Uniyal
+1: This is the only way to guarantee "atomic" file writes.
S.Lott
perfect - thanks
Plumo