I have a list of date in datetime format. This list has a range date between datetime(2018, 1, 1)
to datetime(2020, 12, 31)
.
I iterate through this list using the following code:
for day in days:
# code snippet to get data from each day
My doubt is: How can use os.mkdir()
inside my loop to create a folder structure like below
data
2018
Jan
2018-01-01.csv
2018-01-02.csv
...
Feb
2018-02-01.csv
2018-02-02.csv
...
...
...
2019
Jan
...
Feb
...
...
2020
Jan
...
Feb
...
...
CodePudding user response:
You can create multiple folders with os.makedirs
, it also can ignore if that folder already exists.
for day in days:
path = day.strftime("%Y/%b")
os.makedirs(path, exist_ok=True)
# write your file to path/filename
Or for example:
for day in days:
path = day.strftime(os.path.join("%Y", "%b", "%Y-%m-%d.csv"))
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as file:
file.write("Your Data Here")
Possible placeholders for strftime
can be found on this handy site. You might find it useful to change the intermediate folder names, as the month names won't work particularily well with alphabetical order, so you might want to change that to %m %b
such that the preceding number allows for better sorting.