Closed
Description
New function signature:
def write_to_file(self, new_problem, overwrite=False):
"""
:param overwrite: Whether to overwrite the file at 'new_problem' if it exists
:type overwrite: bool
"""
. . .
Describe the solution you'd like
Check for the existence of the file new_problem
, and do not overwrite it unless overwrite=True
.
One solution: simply raise an error.
if overwrite or not os.path.exists(new_problem):
# write the file as normal
return
elif os.path.isfile(new_problem):
raise FileExistsError(new_problem)
elif os.path.isdir(new_problem):
raise IsDirectoryError(new_problem):
. . .
Describe alternatives you've considered
Or, if the file exists and overwrite == False
, back up the original file with some sort of identifier, and then write to the requested filename.
UUID:
def get_backup_fname(new_problem):
base_name, extension = os.path.splitext(new_problem)
unique_id = uuid.uuid4()
new_fname = f"{base_name}_backup_{unique_id}{extension}"
return new_fname
Timestamp:
def get_next_backup_fname(new_problem):
base_name, extension = os.path.splitext(new_problem)
timestamp = int(time.time()) # OR use strftime('%Y%m%d%H%M%S') for human-readable
new_fname = f"{base_name}_backup_{timestamp}{extension}"
# If user going faster than one file per second
index = 1
while os.path.exists(new_file):
new_file = f"{base_name}_backup_{timestamp}_{index}{extension}"
index += 1
return new_fname
Additional context
Related to pyOpenSci review here: pyOpenSci/software-submission#205 (comment)