【发布时间】:2020-11-10 16:46:37
【问题描述】:
我正在尝试创建一个新的文本文件,其中分配了一个变量作为文件名;将今天的日期添加到创建的每个文件中。虽然继续收到相同的错误-
FileNotFoundError: [Errno 2] No such file or directory: 'TestFileWrite_10/11/2020.txt'
我试过这些方法都没有成功-
使用 str-
today = date.today()
filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")
f = open(str(filename)+'.txt', "w")
f.write(output1)
# output1 var is referenced within another part of the script.
f.close()
使用 %-
today = date.today()
filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")
f = open("%s.txt" % filename, "w")
f.write(output1)
# output1 var is referenced within another part of the script.
f.close()
使用 .format-
today = date.today()
filename = "TestFileWrite" + str(today.strftime("%d/%m/%Y"))
f = open("{}.txt".format(filename), "w")
f.write(output1)
# output1 var is referenced within another part of the script.
f.close()
【问题讨论】:
-
您的文件名中似乎包含
/。这些将被重新解释为文件夹名称分隔符。你的意思是"TestFileWrite_10-11-2020.txt"? -
完全忽略了日期创建,解决了我的问题,谢谢@quamrana
标签: python python-3.x file filenames