Advertisement
LorenKPetrov

Python Mass FileRenamer

Dec 19th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.37 KB | None | 0 0
  1. import os # Imports the OS function
  2. import time # Imports the time function
  3. import glob # Imports the glob function
  4.  
  5. os.system("cls") # Cleans the screen, change this to your relevant console command for your OS.
  6. print "\n What is the current extension of the file?" # Asks the user for the current file extension
  7. ext_0 = raw_input(" > ") # Explains its self, asks the user to set the variable for ext_0
  8.  
  9. os.system("cls")
  10. print "\n What is the new extension of the file?" # I wanted to change some of my pictures extension type from png or bmp to jpg so I just used this to rename it rather than convert it.
  11. ext_1 = raw_input(" > ") # Again, explains its self.
  12.  
  13. os.system("cls")
  14. print "\n What would you like the file to be named?" # Sets a prefix so LKP_ would be what you enter in here!
  15. filename = raw_input(" > ")
  16.  
  17. os.system("cls")
  18. print "\n What is the directory of the files?" # Go from the relevant directory, I currently use C:/ as my main directory because it just makes it easier for my script to run, however you can run it from same directory or even a parent directory.
  19. dir = raw_input(" > ")
  20.  
  21. os.system("cls")
  22. os.chdir(dir) # Uses the OS function to change the directory to the directory of the file
  23. dir_list = glob.glob("*"+ext_0) # Lists all the files that have the same extension type as the user input
  24.  
  25. num_0 = 1 # used in the while statement to add to the file name using my earlier example = LKP_* astrix would be the number so the first file it would make would be LKP_1.jpg
  26. num_1 = len(dir_list) # Counts the amount of files so it knows how many times to run the while code.
  27. num_2 = 0 # This is used in the "less" than for the while.
  28.  
  29. while num_2 < num_1: # I could have used a For loop or something else but I just wrote this as a quick script
  30.     part_1 = dir+dir_list[num_2] # Part one of the os.rename, it makes it easier to see what's going on this way.
  31.     part_2 = dir+filename+str(num_0)+ext_1 # Part two of the os.rename, it makes it easier to see what's going on this way.
  32.     os.rename(part_1,part_2) # Renames all the relevant files.
  33.     print "\n Renamed: "+dir_list[num_2] # Just prints out the number of files renamed, looks rather pretty.
  34.     num_0 = num_0 + 1 # Just adds the count to the loop so it doesn't run infinitely.
  35.     num_2 = num_2 + 1 # See above
  36.  
  37. time.sleep(1) # lets you see it's done for a brief second.
  38. os.system("cls")
  39. print "\n Done!"
  40. time.sleep(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement