Home > other >  How to make a file with a variable as the name
How to make a file with a variable as the name

Time:08-15

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:\Users\taco\PycharmProjects\pythonProject\mygame.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"

CodePudding user response:

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"

  • Related