创建以变量作为文件名的文本文件
Creating Text File with Variable as the File Name
我正在尝试创建一个新的文本文件,并将一个变量指定为文件名;将今天的日期添加到创建的每个文件。尽管继续收到相同的错误-
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()
您必须删除或替换以下斜杠:
filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")
应更改日期格式,例如:
filename = "TestFileWrite_" + today.strftime("%Y%m%d")
或
filename = "TestFileWrite_" + today.strftime("%d_%m_%Y")
另外,'filename'的类型已经是'str',所以不需要使用str()函数:
f = open(filename+'.txt', 'w')
我正在尝试创建一个新的文本文件,并将一个变量指定为文件名;将今天的日期添加到创建的每个文件。尽管继续收到相同的错误-
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()
您必须删除或替换以下斜杠:
filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")
应更改日期格式,例如:
filename = "TestFileWrite_" + today.strftime("%Y%m%d")
或
filename = "TestFileWrite_" + today.strftime("%d_%m_%Y")
另外,'filename'的类型已经是'str',所以不需要使用str()函数:
f = open(filename+'.txt', 'w')