import os def write_atomically(file_path, contents): staging_file_path = f'{file_path}~' try: with open(staging_file_path, 'w') as config_staging_file: config_staging_file.write(contents) config_staging_file.flush() os.fsync(config_staging_file.fileno()) os.replace(staging_file_path, file_path) finally: if os.path.exists(staging_file_path): os.remove(staging_file_path)