[英]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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.