2

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:

enter image description here

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

3
  • The listdir is giving the file names in the path, but the program is being run from a different directory. The code supplies only then name, so it's using the current directory as the path, where no such name exists. Commented Apr 20, 2020 at 3:16
  • So... i need to run the program in the same directory as the folders i want to rename ? Commented Apr 20, 2020 at 3:17
  • You need to add the path prefix back in. os.path.join. Commented Apr 20, 2020 at 3:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.