Created
March 7, 2024 15:07
-
-
Save prince-ravi-leow/a5919a7a3819ac805b7c27b208557fa6 to your computer and use it in GitHub Desktop.
Prevent file overwriting with this simple trick (sysadmins hate him!)
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 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