atomiccreate

Create files and symbolic links in a way that appears to be an atomic file-system operation.

It is sometimes useful that files and symbolic links are created with the intermediate write operations hidden. Temporary files and symbolic links are used and the final update operation is atomic.

Create or update a symbolic link atomically.

This function is similar to os.symlink() but will update a symlink atomically.

class atomiccreate.smart_open(filename, mode='r', use_temp=None, delete_temp_on_error=True, chmod=None, temp_ext='.tmp')

A smarter way to open files for writing.

This class mimics the behaviour of:

with open(filename) as handle:

but with two additional benefits:

  1. When opening a file for write access (including appending) the parent directory will be created automatically if it does not already exist.
  2. When opening a file for write access it is created with a temporary name (with a .tmp extension) and if there are no errors it is renamed automatically when closed. In the case of errors the default is to delete the temporary file, to keep the temporary file call smart_open() with delete_temp_on_error=False. The temporary extension can be overridden with the temp_ext parameter.

The use of a temporary file is automatically disabled when the mode includes 'r', 'x', 'a', or '+'. It can be prevented manually by calling smart_open() with use_temp=False. When a temporary file is used it will be deleted automatically if an exception occurs; this behaviour can be prevented by calling with delete_temp_on_error=False.

For security reasons the temporary files are created with restricted read and write permissions. To maintain the atomic behaviour do not call os.chmod() after smart_open(), instead pass the appropriate file mode permissions with chmod=perms.

Example use:

with smart_open('/tmp/dir/file.txt', 'w') as f:
    f.write('some text')

Indices and tables