【问题标题】:how can i transform datetime correctly to be able to use it as the title of my file?如何正确转换日期时间以便能够将其用作文件的标题?
【发布时间】:2021-06-23 17:25:54
【问题描述】:

这是我的代码。我希望能够创建一个名称由其创建日期组成的文件,但这样它不起作用。

from datetime import date

today = date.today()

myFile=open(today.strftime('%m/%d/%Y'),".txt","w")

myFile.close()

【问题讨论】:

  • / 放在文件名中可能不是一个好主意,因为它可能是不同的目录。此外,您可以使用+".txt" 添加到文件名中。
  • 我认为它不会让您将/ 放在文件名中,它可能会默默地失败。如果您尝试通过 finder/explorer 执行此操作,它会给您一个错误,与其他几个字符相同。只需改用-

标签: python string file datetime


【解决方案1】:
myfile=open(date.today().strftime('%m%d%Y')+".ext","w")

【讨论】:

    【解决方案2】:

    对于文本文件使用 this(WT 表示以文本模式写入)

    from datetime import date
    today = date.today()
    myFile=open(f"{today.strftime('%m_%d_%Y')}.txt","wt")
    myFile.close()
    

    对于二进制文件使用 this(WB 表示以二进制模式写入)

    from datetime import date
    today = date.today()
    myFile=open(f"{today.strftime('%m_%d_%Y')}.bin","wb")
    myFile.close()
    

    对于更高级的场景:

    from datetime import date
    today = date.today()
    with open(f"{today.strftime('%m_%d_%Y')}.txt","wt") as myFile:
        do_something()
        # file close not needed this way
        # myFile holds the variable to access the file such as myFile.write 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2021-12-27
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多