os.rename模块引发了WindowsError,不明白为什么

时间:2017-12-06 22:04:45

标签: python windows python-2.7

以下是一段代码。

import os
def rename_files():
file_list = os.listdir(r"C:\Users\Oleg\Desktop\prank\prank")
print (file_list)
saved_path = os.getcwd()
print("Current Working Directory Is "+saved_path)
for x in file_list:
    print x
    x1 = x.translate(None,"0123456789")
    print x1
    os.rename(x, x1)
rename_files()`

问题在于它给了我一个错误......

Traceback (most recent call last):
File "C:/Python27/rename_files.py", line 13, in <module>
rename_files()
File "C:/Python27/rename_files.py", line 11, in rename_files
os.rename(x, x1)
WindowsError: [Error 2] ?? ??????? ????? ????????? ????

1 个答案:

答案 0 :(得分:0)

您在重命名文件时未使用重新列出的路径,请尝试:

import os

def rename_files(path):
    file_list = os.listdir(path)
    print(file_list)
    for x in file_list:
        print(x)
        x1 = x.translate(None,"0123456789")
        print(x1)
        os.rename(os.path.join(path, x), os.path.join(path, x1))

rename_files(r"C:\Users\Oleg\Desktop\prank\prank")