Programming Foundations with Python >> Lessons >> Use Functions >> Squashing the Bug
Notes on Squashing the Bug
- At the end of the video, he mentions to include the code I show below in bold to further edit the code to include printing the old file_name and the new file_name. I found that after adding this code and running the program, instead of printing an old file_name and a new file_name, you see the new file_name printed twice for each file_name. I think this is because by running the program without this code first, we already changed each file_name within /prank. So the old file_name now IS the new file_name, because, well, we changed it.
IDE input:
import os def rename_files(): #(1) get file names from a folder file_list = os.listdir(r"/Users/africansalami/Downloads/Udacity Full Stack/prank") #print(file_list) saved_path = os.getcwd() print("Current working directory is "+saved_path) os.chdir(r"/Users/africansalami/Downloads/Udacity Full Stack/prank") #(2) for each file, rename filename for file_name in file_list: print("Old Name - "+file_name) print("New Name - "+file_name.translate(None, "0123456789")) os.rename(file_name, file_name.translate(None, "0123456789")) os.chdir(saved_path) rename_files()
SHELL Output
Old Name - .DS_Store New Name - .DS_Store Old Name - athens.jpg New Name - athens.jpg Old Name - austin.jpg New Name - austin.jpg Old Name - bangalore.jpg New Name - bangalore.jpg Old Name - barcelona.jpg New Name - barcelona.jpg Old Name - beijing.jpg New Name - beijing.jpg ...