os.rename()给出了WindowsError:[错误123]文件名,目录名或卷标语法错误

时间:2017-03-14 05:35:51

标签: python windows ubuntu scripting python-os

我编写了一个Python脚本来重命名文件夹中的所有文件。代码是:

import os
import sys
import platform

walk_dir = dir_path = os.path.dirname(os.path.realpath(__file__))

print('walk_dir = ' + walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))

filePathList =[]
for root, subdirs, files in os.walk(walk_dir):
    for filename in files:
        file_path = os.path.join(root, filename)
        filePathList.append(file_path)

total =  len(filePathList)

print str(total) + " files found.\n\n\n"

count = 0
for file in filePathList:
    count = count + 1
    if file == os.path.realpath(__file__):
        continue
    old_file_name = file
    parentDirectories = str(file).split('/')
    dir_lenght = len(parentDirectories)
    new_file_name = ''
    index = 0
    while index < dir_lenght - 1:
        new_file_name = new_file_name + parentDirectories[index] + '/'
        index = index + 1
    new_file_name = new_file_name + parentDirectories[dir_lenght -2] + '_' + parentDirectories[dir_lenght - 1]

    os.rename(old_file_name, new_file_name)

这在ubuntu操作系统上工作正常,但在Windows中它会出错。最后一行' os.rename(old_file_name,new_file_name)'发生错误。错误消息是:

 Traceback (most recent call last):  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 1531, in     globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 938, in run    pydev_imports.execfile(file, globals, locals)  # execute the script
File "E:/Music/Bangla - Copy/reursiveFileRenameAppendFolderName.py", line 67, in     os.rename(old_file_name, new_file_name)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

为什么此脚本在不同的操作系统中表现不同? 如何使这个脚本也在Windows操作系统中工作?

0 个答案:

没有答案