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.")
标签:rename,name,FileNotFoundError,file,print,new,os,image 来源: https://blog.csdn.net/ninnyyan/article/details/89786065