How to make a file with a variable as the name

Question:

I am trying to make a log file for my application but when I try to make the file with a variable as the name I get a "FileNotFound" error.

Example:

log_file_name = str("log" + "/" + str(current_time.month) + "/" + str(current_time.day) + "/" + str(current_time.year) + ".txt")
log_txt = open(log_file_name, "a")

This gives me a FileNotFound error like this

Traceback (most recent call last):
  File "C:UserstacoPycharmProjectspythonProjectmygame.py", line 7, in <module>
    log_txt = open(log_file_name, "a")
FileNotFoundError: [Errno 2] No such file or directory: 'log/8/14/2022.txt'

The below method would give me the same error.

log_txt = open (str("log" + "/" + str(current_time.month) + "/" + str(current_time.day) + "/" + str(current_time.year)) + ".txt", "a")

But if I do something simple like this it creates the file as it should:

log_txt = open("log.txt", "a")

Edit I forgot to add that the same happens above when using "a+" instead of "a"

Asked By: TaCo

||

Answers:

Firstly, instead of concatenating multiple strings, just use f-string which would make your code look something like this:

log_file_name = f"log/{current_time.month}/{current_time.day}/{current_time.year}.txt")

It does the same thing but is a bit easier on the eyes.

Now to answer your question, the reason you’re getting this exception is you’re using / to seperate the variables which would trick python into thinking the variables are directories.

To fix this, remove the / in your filename string, so that it would look like this:

f"log{current_time.month}{current_time.day}{current_time.year}.txt"

Answered By: muneeb_mughal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.