Last active
August 29, 2015 14:26
-
-
Save ConConovaloff/ac5fd234f8a722fa0d93 to your computer and use it in GitHub Desktop.
Python: safely write to a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def safe_write_file(file_path, data, tmp_path_generator_callback=None): | |
""" | |
:type file_path: str | |
:param data: what write | |
:type tmp_path_generator_callback: function | |
""" | |
if os.path.isdir(file_path) or os.path.islink(file_path): | |
raise Exception('File %s must not be a link or directory' % file_path) | |
if tmp_path_generator_callback is None: | |
tmp_path_generator_callback = get_file_path_tmp_file | |
# get path to temporary file | |
file_path_tmp = tmp_path_generator_callback(file_path) | |
try: | |
# write to temporary file | |
with open(file_path_tmp, 'w+b') as file_path_tmp_obj: | |
file_path_tmp_obj.write(data) | |
# copy permissions for temporary file (included chattr) | |
if os.path.isfile(file_path): | |
shutil.copystat(file_path, file_path_tmp) | |
# moved file | |
os.rename(file_path_tmp, file_path) | |
finally: | |
# if something wrong, delete temporary file | |
try: | |
os.remove(file_path_tmp) | |
except: | |
pass | |
def get_file_path_tmp_file(file_path): | |
""" Returns a recommended path for a temporary file | |
:type file_path: str | |
:rtype: str | |
""" | |
result_file_path = file_path + '_tmp' | |
while os.path.exists(result_file_path): | |
result_file_path + str(random.randint(0, 9)) | |
return result_file_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment