safesave: Safely write files

This module provides a method to safely overwrite a file. If it fails, then the file was not overwritten.

Usage:

with SaveTextFile(filename) as f:
    print(..., file=f)
    f.write(...)

or:

try:
    f = SaveTextFile(filename)
    print(..., file=f)
    f.write(...)
    f.close()
except IOError as e:
    f.close(e)
class SaveBinaryFile(filename, critical=False)

Bases: SaveFile

SaveFile specialized for Binary files

Parameters:
filename : str

Name of file.

critical : bool, optional

If critical, have operating system flush to disk before closing file.

class SaveFile(filename, open=<built-in function open>, critical=False)

Bases: object

Provide a file-like object to safely overwrite existing files.

Data is first written to a temporary file, then that file is renamed to the desired filename when it is closed. That way, a partial write of the replacement file will not overwrite the original complete file. If used in a with statement, then the temporary file will always be removed on failure. Defaults to writing binary files. Locking is not provided.

Parameters:
filename : str

Name of file.

open : function taking a filename to write
critical : bool, optional

If critical, have operating system flush to disk before closing file.

Attributes:
name : str

Name of file.

close(exception=None)

Experimental API . Close temporary file and rename it to desired filename

If there is an exception, don’t overwrite the file.

writable()

Experimental API . Only writable files are supported

write(buf)

Experimental API . Forward writing to temporary file

writelines(lines)

Experimental API . Forward writing to temporary file

class SaveTextFile(filename, newline=None, encoding=None, critical=False)

Bases: SaveFile

SaveFile specialized for Text files”

Parameters:
filename : str

Name of file.

encoding : str, optional

Text file encoding (default is UTF-8)

newline : open()’s optional newline argument
critical : bool, optional

If critical, have operating system flush to disk before closing file.