sud*_*sud 5 python datetime python-3.x
我正在编写python程序,以使用当前时间和日期来重命名文件,但出现以下错误。
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
Run Code Online (Sandbox Code Playgroud)
我的代码
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")
Run Code Online (Sandbox Code Playgroud)
输出
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
Run Code Online (Sandbox Code Playgroud)
请让我知道os.rename在传递z和目标新字符串时我在函数中犯什么错误。
>>> str(datetime.datetime.now())
'2017-08-10 19:52:39.057834'
Run Code Online (Sandbox Code Playgroud)
注意冒号(:),用于将驱动器与路径的其余部分分开。您不能在Windows的文件名中使用它。
我建议:
datetime.datetime.now().replace(":","_")
Run Code Online (Sandbox Code Playgroud)
(并且也许也要删除空格,或者为您的日期使用兼容的自定义格式)