通过省略数字重命名文件形成文件名错误

时间:2018-08-29 15:57:46

标签: python-2.7

我尝试遵循在线课程中的示例来创建一个函数,通过省略文件名中的数字来更改文件名。但是我遇到了这个错误:

os.rename(file_name, file_name.translate(None,"0123456789"))
WindowsError: [Error 2] The system cannot find the file specified

但是代码在我观看的视频上运行正常

import os

def rename_files():
    # (1) get file naems from a folder
    file_list = os.listdir(r"C:\prank")
    #print (file_list)
    saved_path = os.getcwd()
    print (" Currnet Wroking Directory is " +saved_path)
    os.chdir(r"C:\prank")


    # (2) for each file, rename filename
    for file_name in file_list:
        os.rename(file_name, file_name.translate(None,"0123456789"))
        os.chdir (saved_path)



rename_files()

1 个答案:

答案 0 :(得分:0)

尝试一下,无需更改工作目录,这不是一个好习惯。另外,如果要在C:中重命名文件,则可能必须以管理员身份执行代码。

import os

def rename_files():
    # directoy with the files
    directory=r"C:\prank"
    # (1) get file names from a folder 
    file_list = os.listdir(directory) # this is the folder with the files
    # (2) for each file, rename filename
    for file_name in file_list:
        new_name=''.join([s for s in file_name if s not in ['0','1','2','3','4','5','6','7','8','9']]) # remove numbers 
        os.rename(os.path.join(directory,file_name),os.path.join(directory,new_name))

rename_files()