简体   繁体   中英

Rename Multiple folder in a directory with python

I want to automate renaming multiple folders in a folder using 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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