On one of my projects I wanted to save all the requests the application was receiving, creating my own log. I didn't want to have all the requests in one big file but instead in folders indicating the year, month, day and time of the request.

When the request comes in the file is saved in the folders:
logs/Year/Month/Day/Time.txt

So everytime a request comes in it looks like this:

`-- 2019     # -- Year
    `-- 09        # -- Month
        `-- 28          # -- Day
            |-- 21:44:35.txt   # -- Time
            |-- 21:45:20.txt
            |-- 21:45:57.txt
            |-- 21:47:18.txt
            |-- 21:48:49.txt
            `-- 21:57:09.txt

The complete code

import datetime
import os

data = "The data that you want to write in the file"

# Find out what the year, month, day and time is
now = datetime.datetime.now()
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
time = now.strftime("%H:%M:%S")

# Add the time and the .txt extension as the filename
filename = time + ".txt"

# Construct the path
path = "logs/{0}/{1}/{2}/".format(year, month, day)

# Check if the path exists. If it doesn't create the directories 
if not os.path.exists(path):
    os.makedirs(path)

# Create the file
with open(os.path.join(path, filename), 'w') as f:
    f.write(data)

Breakdown

Imports

import datetime
import os

Data and Dates

You can change how the year, month, day and time are presented with strftime. If you want to view all directives of strftime then visit this reference page made by Will Mccutchen: http://strftime.org/.

data = "The data that you want to write in the file"

now = datetime.datetime.now()
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
time = now.strftime("%H:%M:%S")

Filename

I want my files to be .txt files so I have added that to the filename string:

filename = time + ".txt"

Path [ directory where the file will be created ]

Then I constructed the path using pythons string formatting method .format() :

path = "logs/{0}/{1}/{2}/".format(year, month, day)

Create directories

After that we check if the path already exists, and if it doesn't create all the folders with os.makedirs:

if not os.path.exists(path):
    os.makedirs(path)

Write the data

And finally, create the file at the path we want it to and write the data to it. By using os.path.join(path, filename) we are linking "2019/09/28/" + "21:57:09.txt"

with open(os.path.join(path, filename), 'w') as f:
    f.write(data)