Find the right nanodegree program for you.

Start Learning

Have you ever had to rename a file? What about 50? Or 1000? At some point, the only reasonable solution is to write a program to do the renaming for you.

At Udacity, we run into this problem pretty frequently. Have you ever wondered how the Udacity courses actually get up onto udacity.com?

We have to upload them. The program we use to do that expects a very specific naming structure. Check out this segment of videos for a lesson from Intro to Object Oriented Programming:

Lesson01

What happens if we need to add a video between 11_s_Add a Loop.mp4 and 12_l_Make the Program Wait Longer.mp4?

For our uploader to work, we’d need to increment all the videos with numbers greater than 11 (so 12 becomes 13, 13 becomes 14, etc…) and then we could add our new video in as 12.

Let’s solve this problem by writing code! Here is how we do it:

  1. Start small: First, we’ll establish a process and figure out how to rename just one file.
  2. Break it down: Start with location. Your computer needs to know where your file is in order to rename it. This is the function:
    • os.path.abspath(path) where path is the directory where your file is.

    In my case, path is ‘/Users/andrewbrown/Desktop/movie_test’

  3. Find the function to rename: The function to rename files is:
    • os.rename(old_file_name, new_file_name)

    Example: os.rename(“12_l_Making the Program Wait Longer.mp4”, “13_l_Making the Program Wait Longer.mp4”)

  4. Test it: Run the program to make sure you can rename one file.
  5. Loop it: If your test works, add a loop to go through and rename all the files you want to rename.
  6. Consider edge cases: What if your program is renaming a file to something that already exists in the folder? One solution is to let your computer give you an exception error, and you can handle these cases manually after the program has run.
  7. Put it all together in a function: See below:
    rename-py

Did it work? Yes! Now I can just add my new video 12 and I’m all set!

Be careful when running this code (you can get the code here). I had tested this a few times by printing the old and new file names and making sure everything made sense. The os.rename() function will do exactly what you tell it to and that can be very dangerous. Test before you use it!

Want some practice? In Udacity’s new foundational programming course, Intro to Object Oriented Programming, you can practice this function in a mini project called Secret Message, where you’ll write a secret message that can be decoded by renaming files. The course also has five other fun mini projects where you’ll learn foundational programming concepts!

Check out the course