简体   繁体   中英

Python os.rename windowsError

I've got some code that I'm working on to add the timestamp to the start of a file in windows and I can't get it to work properly.

for root, dirs, files in os.walk('D:\\development\\test'):
    for f in files:
        fullpath = os.path.join(root + os.sep, f)
        print fullpath
        if fullpath.endswith('txt'):
            d = str(mod_date(fullpath))
            dt = d.split()
            newName = str(dt[1]) + '_' + f
            newNameFull = os.path.join(root + os.sep, newName)
            print newNameFull
            os.rename(fullpath, newNameFull)

This will print properly:

fullpath D:\development\test\New Text Document (2).txt
newNameFull D:\development\test\11:44:04.464341_New Text Document (2).txt

But the os.rename will give a windowsError:

Traceback (most recent call last):
  File "D:/Python27/Scripts/getTime.py", line 17, in <module>
os.rename(fullpath, newNameFull)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

Any ideas? I've tried many iterations of the // / \\ but can't find the right one.

Windows does not allow file names to contain a : character (excepting in the drive identifier). You'll need to alter your timestamp to use a different format.

MSDN reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM