Gshare
Gshare

Reputation: 9

Python Iterating through Directories and Renaming

I am trying to iterate through a list of subdirectories and then opening the files within that subdirectory and renaming the files to lowercase. Here is my code:

for root, subdirs, pics in os.walk(rootdir):
  for pic in pics:
    if pic.endswith('.jpg'):
        picpath = os.path.join(pic)
        #print pic
        print picpath
        #os.rename(pic, pic.replace(" ", "-").lower())
        os.rename(picpath, picpath.replace(" ", "-").lower())

I then get:

Traceback (most recent call last): File "imageresizing-renamefiles.py", line 19, in os.rename(picpath, picpath.replace(" ", "-").lower()) OSError: [Errno 2] No such file or directory

My file structure is a root directory where the code runs from and within that folder are the following folder1 with Image1jpg and Image2jpg, folder2 with Image3jpg and Image4jpg and so on. I want to iterate through each to rename the files (not the folders) to lower case names.

Appreciate any help.

Upvotes: 0

Views: 631

Answers (2)

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

you have to append the directory name to your path or os.rename is unable to find the proper directory where to apply the rename.

That said, your conversion to lowercase complicates the task. lowercase must only be applied to the basename (that would work on Windows filesystem because case doesn't matter, but would fail on Linux if some directories of the path contain uppercase letters: fortunately, you cannot rename a whole dirtree with a single rename command)

And the match for .jpg extension should be done regardless of the casing, specially if you want to convert picture names to lowercase: extensions are likely to be in uppercase too (like all those DCIM cameras)

for root, subdirs, pics in os.walk(rootdir):
  for pic in pics:
    if pic.lower().endswith('.jpg'):  # more powerful: fnmatch.fnmatch(pic,"*.jpg")
        os.rename(os.path.join(root,pic), os.path.join(root,pic.replace(" ", "-").lower()))

Upvotes: 1

cxw
cxw

Reputation: 17041

picpath = os.path.join(root, pic)
                    #  ^^^^^

looks like it should do the job. Per the docs,

Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).

That is why you are getting a "No such file" error: you are asking for the filename in the current directory, which isn't root at the point the error happens.

Upvotes: 1

Related Questions