Reputation: 379
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
Upvotes: 2
Views: 4765
Reputation: 2455
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.
Upvotes: 3