使用python重命名目录中的多个文件夹

使用python重命名目录中的多个文件夹,python,Python,我想使用python自动重命名文件夹中的多个文件夹。这是我使用的代码: import os path = r"C:/Users/Dimas hermanto/Documents/Data science gadungan/Belajar python/Computer vision and Deep learning/Flask tutorial 2/stanford-dogs-dataset/test" directory_list = os.listdir(path)

我想使用python自动重命名文件夹中的多个文件夹。这是我使用的代码:

import os

path = r"C:/Users/Dimas hermanto/Documents/Data science gadungan/Belajar python/Computer vision and     
Deep learning/Flask tutorial 2/stanford-dogs-dataset/test"

directory_list = os.listdir(path)




for filename in directory_list:
    src = filename
    dst = filename[filename.find('-') + 1:]

    # print(dst)

    os.rename(src, dst)

print("File renamed!")
这是我要重命名的文件夹的名称格式:

我要做的是分割文件名字符串,使其只显示为

Chihuahua 
Japanese_spaniel, 
Maltese_dog,
Pekinese, 
Shih_tzu, 
etc.
但当我运行代码时,它返回:

Exception has occurred: FileNotFoundError
[WinError 2] The system cannot find the file specified: 'n02085620-Chihuahua' -> 'Chihuahua'

我该怎么做才能解决这个问题?当我尝试打印
dst
变量时,它返回所需目标名称的列表。所以我假设我已经设置了正确的文件夹路径,src和dst不是绝对路径,所以它试图从python脚本的目录中重命名一个文件


您只需将
os.rename(src,dst)
替换为
os.rename(os.path.join(path,src),os.path.join(path,dst))
即可解决此问题。

listdir给出了路径中的文件名,但程序是从不同的目录运行的。代码只提供名称,所以它使用当前目录作为路径,而不存在这样的名称。所以。。。我需要在与我要重命名的文件夹相同的目录下运行该程序?哇,你说得对。非常感谢。您需要重新添加路径前缀
os.path.join