[英]Creating Text File with Variable as the File Name
I'm trying to create a new text file with a variable assigned as the name of the file;我正在尝试创建一个新的文本文件,其中一个变量被指定为文件名; to add todays date to each file created.
将今天的日期添加到创建的每个文件中。 Though continue to receive the same error-
虽然继续收到相同的错误 -
FileNotFoundError: [Errno 2] No such file or directory: 'TestFileWrite_10/11/2020.txt'
I've tried these methods with no success-我试过这些方法都没有成功-
Using str-使用 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()
Using %-使用 %-
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()
Using .format-使用 .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()
You have to remove or replace the slash bar in:您必须删除或替换斜杠:
filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")
The date format should be changed, for example:应更改日期格式,例如:
filename = "TestFileWrite_" + today.strftime("%Y%m%d")
or或者
filename = "TestFileWrite_" + today.strftime("%d_%m_%Y")
Moreover, the type of 'filename' is already 'str', so there is no need to use str() function:而且,'filename' 的类型已经是 'str',所以不需要使用 str() 函数:
f = open(filename+'.txt', 'w')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.