python - 如何在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 但没有将文件作为输出
解决方案
我的假设是该文件应该是一个*.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
推荐阅读
- typescript - 强制字段的通用接口
- linkedin - 检索 Linkedin Video Post (ugcPost API) 的缩略图
- python - 如何修改这个斐波那契数列问题?
- url-rewrite-module - IIS URL重写删除部分路径
- reactjs - 为什么我的服务人员没有注册?
- batch-file - 使用批处理在 powercli 中运行命令
- css - 在 VStudio MVC 5 应用程序的 html 页面中引用 css 不起作用
- javascript - """ 之间的 Javascript 正则表达式文本
- terraform - 如何在 Terraform 中初始化远程状态?
- jquery - 使用非类选择器选择输入类型