11

What's the recommended way to replace a file atomically in Python?

i.e. if the Python script is interrupted, there is a power outage etc. files do not have a high probability of ending up in an inconsistent state (half written to the disk).

A solution for Linux/UNIX platforms is preferred.

(I know getting 100% atomic operations might depend on your file system, but at least make the chances for the corruption low.)

martineau
  • 119,623
  • 25
  • 170
  • 301
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435

1 Answers1

16

Create a new file and os.rename() it over the existing file. This is atomic on most platforms under most conditions.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175