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.")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章