我正在编写python程序,以使用当前时间和日期来重命名文件,但出现以下错误。
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
我的代码
import os import sys import datetime file=open("C:\\Users\\sun\\Desktop\\ping",'w') z=file.name dt = str(datetime.datetime.now()) file.close() print(z) new ='C:\\Users\\sun\\Desktop\\ping_'+dt+'.txt' os.rename(z,new) print("i am done")
输出
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
请让我知道os.rename
在传递z和目标新字符串时我在函数中犯什么错误。
>>> str(datetime.datetime.now()) '2017-08-10 19:52:39.057834'
注意冒号(:
),用于将驱动器与路径的其余部分分开。您不能在Windows的文件名中使用它。
我建议:
datetime.datetime.now().replace(":","_")
(并且也许也要删除空格,或者为您的日期使用兼容的自定义格式)