Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a file with a variable as the name

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading