【问题标题】:Creating Text File with Variable as the File Name创建以变量为文件名的文本文件
【发布时间】:2020-11-10 16:46:37
【问题描述】:

我正在尝试创建一个新的文本文件,其中分配了一个变量作为文件名;将今天的日期添加到创建的每个文件中。虽然继续收到相同的错误-

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

【问题讨论】:

  • 您的文件名中似乎包含/。这些将被重新解释为文件夹名称分隔符。你的意思是"TestFileWrite_10-11-2020.txt"
  • 完全忽略了日期创建,解决了我的问题,谢谢@quamrana

标签: python python-3.x file filenames


【解决方案1】:

您必须删除或替换以下斜杠:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2020-05-23
    • 1970-01-01
    • 2018-09-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多