Ensuring a Folder, Path to a File exists (Auto-making directories)
Useful for when you're writing log and result files with unique folders
Introduction
In my research, one of the most common things I need to do is write log and output files to the disk. to keep things organized, I usually group my output files by a date-time string, in a “close to ISO:8601” format. this makes it easy to sort and find these files later. However, the able to action that python will do is if you try to save to A folder that does not exist, and error is thrown. I include this snippet of code into every new project I start.
The Code
import os
import datetime
def automkdir(filename):
if bool(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename), exist_ok=True)
def datetime_string(_dt=datetime.datetime.now().strftime('%Y%m%d_%H%M%S'), current=False):
if current:
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
return _dt
That’s about it.
How does it Work and What Happens When it Runs?
Keep reading with a 7-day free trial
Subscribe to Sean Grogan Tutors to keep reading this post and get 7 days of free access to the full post archives.