[英]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?我能做些什么来解决这个问题吗?
One issue was the closing parentheses, also the date format contain / (slash ex:07/07/21) which will make the filename with slash ie not a valid name in windows as it makes it a path.一个问题是右括号,日期格式也包含 /(斜杠,例如:07/07/21),这将使文件名带有斜杠,即在 Windows 中不是有效名称,因为它使其成为路径。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.