简体   繁体   中英

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-

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()

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM