Python | Rename Files

You’ve just come back from an awesome vacation
at the beach and you took tons of photos you want to share with your friends. But oh no! All of the file names are barely decipherable
when you copy them over from your camera. Let’s say I did the work of dragging and
dropping my images into different directories, one of the beach, one of friends, and one
of the resort. I could of course manually rename the files,
but it sounds like a pain to enter a new name for each file. To keep it simple, I want to rename each of
the files to the name of the parent directory plus a number, and keep the same file extension. So IMG_101 in the beach directory will become
beach1.jpg, then beach2.jpg, and the images in the friends directory will become friends1.jpg
and so on. So where do we start? In our previous video on Pathlib, we explained
how to construct a path using our current directory as the base, and then we can nest
our photos directory. We know that our beach, friends and resort
directories are nested under photos, so we’ll want to iterate through each folder in the
path. Except we can’t iterate the path itself,
but we can get at the items with iterdir(). If I print the items, we see there is a txt
file that we’ll want to exclude from our process, so we can check if the item is a
directory. Now we’re at the point where we want to
iterate through the items in the nested directories, with each image being assigned a number. So we’ll initialize a counter variable for
each folder, and then we’ll iterate through the folder contents, and this time we can
check if the item is a file instead of a directory. Now we have the information to construct our
new_file name. We can concatenate the name of the folder,
the counter number, and the suffix or extension of the original file. Notice the problem if I left my code as it
is? We can’t treat integers as strings, so I’ll
convert counter to a string. Then we can rename our current file with our
path, then the folder name, and finally our new_file. It’s important to construct this path correctly,
or else your files will be moved to a different directory. And then our final step is to increment the
counter, or else all of the files in a directory would have the same number. Once we run our code, we can see that all
of the images nested under the photos directory have been renamed with our new naming convention.

Daniel Ostrander

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *