首页 > 解决方案 > 如何在python中打开一个名称附加日期的文件?

问题描述

我正在尝试在 python 中使用 open 方法创建一个文件,其中在我给定的文件名中将使用 datetime 方法附加日期,如下所示

import datetime
f=open('myfile.txt_'+str(datetime.datetime.now()),'w')
print(f.name)

我收到一个错误

File "C:/Users/nitjoshi2/PycharmProjects/Lab/list.py", line 2, in <module>
f=open('myfile.txt_'+str(datetime.datetime.now()),'w')
OSError: [Errno 22] Invalid argument: 'myfile.txt_2019-01-24 
01:12:42.395125'

请解释错误,因为我可以在错误消息中看到所需的输出,即 myfile.txt_2019-01-24 01:12:42.395125 但没有将文件作为输出

标签: python

解决方案


我的假设是该文件应该是一个*.txt文件,因此您正在创建文件名,myfile.txt_2019-01-24而不是myfile_2019-01-24.txt这是一个简单的修复。

此外,建议您使用它,with open() as f而不是f=open()因为它会自动关闭文件,您无需f.close().

编辑

尽管正如@jasonharper 所指出的,您不能使用带有冒号的文件名,因此您需要立即对其进行格式化。

import datetime
with open('myfile{}_.txt'.format(strftime('%Y-%m%d %H-%M', datetime.datetime.now())),'w') as f:
    print(f.name)
    #myfile_2019-01-24 01-12-42 .txt

推荐阅读