I am writing python program to rename the file with current time & date, but I get below error.
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
my code
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")
output
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect
Please let me know what mistake I am making for os.rename
function when passing z & destination new strings.
>>> str(datetime.datetime.now())
'2017-08-10 19:52:39.057834'
notice the colons (:
) which are used to separate drive from the rest of the path. You cannot use that in a filename on windows.
I'd suggest:
datetime.datetime.now().replace(":","_")
(and maybe get rid of the spaces too, or use a compatible custom format for your date)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With