0

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()
2
  • 2
    You seem to have / in your filenames. These will be re-interpreted as folder-name delimiters. Did you mean "TestFileWrite_10-11-2020.txt"? Commented Nov 10, 2020 at 16:49
  • Completely overlooked the date creation, fixed my issue, thank you @quamrana Commented Nov 10, 2020 at 16:54

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.