Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect

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.

like image 658
sud Avatar asked Aug 10 '17 17:08

sud


1 Answers

>>> 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)

like image 119
Jean-François Fabre Avatar answered Sep 23 '22 10:09

Jean-François Fabre