Skip to content
Advertisement

Using a variable as a Filename Python

I cannot get using a variable in the filename to work without throwing an error.

def logData(name, info):
    currentTime = datetime.datetime.now()
    date = currentTime.strftime("%x")
    
    filename = "{}_{}.txt".format(name, date)

    f = open(filename, "a")
    f.write(info)+ 'n')
    f.close()

I have tried formatting the string as shown above as well as concatenating the variables.

Is there anything I can do to solve this?

Advertisement

Answer

One issue was the closing parentheses, also the date format contain / (slash ex:07/07/21) which will make the filename with slash i.e not a valid name in windows as it makes it a path.

Solution with least change to your logic:

import datetime

def logData(name, info):
    currentTime = datetime.datetime.now()
    date = currentTime.strftime("%Y-%m-%d")
    
    filename = "{}_{}.txt".format(name, date)
 
    with open(filename,"a+") as f:
        f.write(f'{info}n')

logData('my_file',"test")
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement