简体   繁体   English

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

[英]Rename Multiple folder in a directory with python

I want to automate renaming multiple folders in a folder using python.我想使用 python 自动重命名文件夹中的多个文件夹。 This is the code i use:这是我使用的代码:

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!")

This is the name format of the folders i want to rename:这是我要重命名的文件夹的名称格式:

在此处输入图像描述

What i'm trying to do is slice the filename string so it'll only came out as我想要做的是切片文件名字符串,所以它只会出现

Chihuahua 
Japanese_spaniel, 
Maltese_dog,
Pekinese, 
Shih_tzu, 
etc.

But when i run the code, it returns:但是当我运行代码时,它返回:

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

What should i do to fix this?我应该怎么做才能解决这个问题? When i try to print the dst variable, it return the list of desired target names.当我尝试打印dst变量时,它返回所需目标名称的列表。 So i assume that i already set the right folder path所以我假设我已经设置了正确的文件夹路径

The src and dst aren't the absolute path, so it's trying to rename a file from the directory of the python script. src 和 dst 不是绝对路径,因此它试图从 python 脚本的目录中重命名文件。

You should be able to fix this just by replacing os.rename(src, dst) with os.rename(os.path.join(path, src), os.path.join(path, dst)) to specify absolute path.您应该可以通过将os.rename(src, dst)替换为os.rename(os.path.join(path, src), os.path.join(path, dst))来指定绝对路径来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM