【发布时间】:2019-06-12 22:21:04
【问题描述】:
我正在尝试创建一个日志系统,它将程序遇到的所有异常写入一个新文件。为了实现这一点,我在创建字符串时使用了 asctime() 函数。但是,当我跑步时,我得到了这个错误:
OSError: [Errno 22] 无效参数:'C:\Users\User\Desktop\VendSend Log Wed Jun 12 17:16:56 2019.txt'
这是我的代码:
reporter_name='C:\\Users\\User\\Desktop\\VendSend Log '+time.asctime()+'.txt'
fh = open(reporter_name,'w')
fh.write('-----VENDORS WITH NO EMAILS-----')
f_len = len(vendor_removed)
fcount = 0
while fcount < f_len:
fh.write(vendor_removed[fcount])
fh.write()
fcount += 1
【问题讨论】:
-
文件名中不能有冒号。使用下划线 (
_) 之类的 -
冒号来自 asctime() 函数。我将如何更改它并继续在文件名中输入时间和日期
-
通常,您会使用一个时间函数来返回可以在文件名中使用的内容,例如
time.time。如果您希望它可读,您可以使用,例如,str.replace删除冒号。 -
time模块大部分被datetime模块所取代。类似datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')或iso的快捷方式 -
@roganjosh:正要提出同样的建议。与
asctime之类的东西相比,它的优势在于该日期格式将按日期字符串按 ASCII 顺序排序,因此按文件名排序会使它们以正确的顺序排列。
标签: python