For Nektoon I’m implementing a storage service in Python. It will work with individual text files that it exposes over a REST API.
I struggled a bit with how to correctly handle file overwrites. In the end I came up with this code:
import os import portalocker if os.name == 'posix': # Rely on the atomicity of Posix renames. rename = os.rename else: def _rename(src, dst): """Rename the file or directory src to dst. If dst exists and is a file, it will be replaced silently if the user has permission. """ if os.path.exists(src) and os.path.isfile(dst): os.remove(dst) os.rename(src, dst) def write(filename, contents): filename_tmp = filename + '.TMP' with open(filename_tmp, 'a') as lockfile: portalocker.lock(lockfile, portalocker.LOCK_EX) with open(filename_tmp, 'w') as out_file: out_file.write(contents) rename(filename_tmp, filename) There are two important parts here.
...