I cannot get using a variable in the filename to work without throwing an error.
JavaScript
x
10
10
1
def logData(name, info):
2
currentTime = datetime.datetime.now()
3
date = currentTime.strftime("%x")
4
5
filename = "{}_{}.txt".format(name, date)
6
7
f = open(filename, "a")
8
f.write(info)+ 'n')
9
f.close()
10
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:
JavaScript
1
13
13
1
import datetime
2
3
def logData(name, info):
4
currentTime = datetime.datetime.now()
5
date = currentTime.strftime("%Y-%m-%d")
6
7
filename = "{}_{}.txt".format(name, date)
8
9
with open(filename,"a+") as f:
10
f.write(f'{info}n')
11
12
logData('my_file',"test")
13