os.rename() FileNotFoundError

由于文件名中有一些特殊字符影响了文件的读取,因此需要把文件名中的特殊字符全部去掉,在使用os.rename()给文件重新命名时,遇到了FileNotFoundERROR的问题。

原代码如下:

import os

directory = "your_path"

for image_file in os.listdir(directory):
    if image_file.endswith(".jpg"):
        new_name = image_file.replace(",","").replace("=","").replace("&","")
        print("old_name:",image_file)
        print("new_name:",new_name)
        os.rename(image_file,new_name)
    else:
        print("not valid file.")

后来发现是因为没有打开相应的文件夹

加入os.chdir(directory)即可

修正后的代码如下:

import os

directory = "your_path"

for image_file in os.listdir(directory):
    if image_file.endswith(".jpg"):
        new_name = image_file.replace(",","").replace("=","").replace("&","")
        print("old_name:",image_file)
        print("new_name:",new_name)
        ###########
        os.chdir(directory)
        ###########
        os.rename(image_file,new_name)
    else:
        print("not valid file.")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章