Reputation: 45
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-
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-
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()
Upvotes: 0
Views: 3351
Reputation: 61
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:
f = open(filename+'.txt', 'w')
Upvotes: 1