4

I tried to rename directories in MacOS, even have used codes of others but os.rename still throws me errors, I give the full path of my directories and their new names as path. May someone help to solve this problem? thanks in advance

import os

directory = "/../"
dirs = next(os.walk(directory))[1]
for file in dirs:
    path = os.path.join(directory, file)
    target = os.path.join(directory, '/' + file.replace('.','/'))
    os.rename(path, target)

with dash

[Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/m/01kk_s6'

without dash

FileNotFoundError: [Errno 2] No such file or directory: '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m.01kk_s6' -> '/Users/Kakadu/Desktop/dogs_vs_cel/MsCelebV1/MsCelebV1-Faces/m/01kk_s6'

P.S file exists and os.rename works when I do rename the file to the same name

 target = os.path.join(directory, file)
 os.rename(path, target)

And by the way, I'm trying to rename the directories(full of images) inside the directory, maybe something is in here.Btw, when I try just to use os.rename on images ( not on directories full of images ) it works fine

Ivan Shelonik
  • 1,958
  • 5
  • 25
  • 49

1 Answers1

1

When renaming something to /j/k/l/m/foo, it is important that directory m exists. If not, you must mkdir m.

Just before your rename call, do this:

    os.makedirs(os.path.dirname(target), exist_ok=True)
J_H
  • 17,926
  • 4
  • 24
  • 44