I have a very common pattern in my python code where I check if a file exists at a given path, raise an exception if it does and if not make all the parent directories. This will help DRY out my code and enforce a consistent logic for file creation throughout the code base.
I could call it prepare_output_path, possible code below, and it would go in the __core__.py file
def prepare_output_path(filename, overwrite=False, err_msg='{} file already exists'):
r"""
Checks if a file already exists and should not be overwritten, creating
intermediate directories as needed if the file will be created.
"""
if os.path.exists(filename) and not overwrite:
raise FileExistsError(err_msg.format(filename))
#
os.makedirs(os.path.split(filename)[0], exist_ok=True)
I have a very common pattern in my python code where I check if a file exists at a given path, raise an exception if it does and if not make all the parent directories. This will help DRY out my code and enforce a consistent logic for file creation throughout the code base.
I could call it
prepare_output_path
, possible code below, and it would go in the__core__.py
file