Skip to content

Instantly share code, notes, and snippets.

@prince-ravi-leow
Created March 7, 2024 15:07
Show Gist options
  • Save prince-ravi-leow/a5919a7a3819ac805b7c27b208557fa6 to your computer and use it in GitHub Desktop.
Save prince-ravi-leow/a5919a7a3819ac805b7c27b208557fa6 to your computer and use it in GitHub Desktop.
Prevent file overwriting with this simple trick (sysadmins hate him!)
def overwhy(dir, basename, ext):
"""
Prevent file overwriting by appending formatted date+timestamp for non-unique filename.
Example:
Following non-unique filename query:
dir: output_dir/, basename: results, ext:txt
Yields:
"output_dir/result_20240307_160534.txt"
"""
import time
from pathlib import Path
t_str = time.strftime("%Y%m%d_%H%M%S")
basepath = Path(dir) / f"{basename}.{ext}"
if not basepath.exists():
result = str(basepath)
else:
result = str(Path(dir) / basename) + "_" + t_str + "." + ext
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment