Samstag, 4. Dezember 2010

Batch File Renaming with Python

I bet everyone has already had this problem. You have a couple of hundreds of files (e.g. photos) and want to rename them all at once using some pattern.

I woke up today and asked myself, why not write a small python script. Here it is:



  1. #!/usr/bin/env python
  2. import re
  3. import os
  4. # regex matching the file name blablaqwe123456.txt
  5. regex = '^s_Entrepreneurship_Corner_Podcasts_(\S+)(\d\d)(\d\d)(\d\d)\.(txt)$'
  6. # prepare the regex
  7. r = re.compile(regex)
  8. # list files in the current directory
  9. all = os.listdir('.')
  10. for fname in all:
  11. m = r.match(fname)
  12. if m:
  13. # extract the different parts from the old name
  14. name = m.group(1)
  15. year = "20" + m.group(2)
  16. month = m.group(3)
  17. day = m.group(4)
  18. ext = m.group(5)
  19. # create the new name
  20. newfname = year + "-" + month + "-" + day + "-" + name + "." + ext
  21. # rename the file
  22. print "renaming " + fname + " to " + newfname + "..."
  23. os.rename(fname, newfname)

Feel free to use it!