我正在编写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
请告诉我在传递z&时,我对os.rename
功能的错误。目的地新字符串。
答案 0 :(得分:5)
>>> str(datetime.datetime.now())
'2017-08-10 19:52:39.057834'
注意冒号(:
),用于将驱动器与路径的其余部分分开。你不能在Windows上的文件名中使用它。
我建议:
datetime.datetime.now().replace(":","_")
(也许也可以摆脱这些空间,或者使用兼容的自定义格式)