Advertisement
mengyuxin

meng.renameFilename.py

Jan 3rd, 2018
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. #! python3
  2. # renameFilename.py - Renames filenames with American MM-DD-YYYY date format to European DD-MM-YYYY.
  3.  
  4. import shutil
  5. import os
  6. import re
  7.  
  8. destFolder = '.\\#temp'
  9.  
  10. # Create a regex that matches files with the American date format.
  11. datePattern = re.compile(r'''^(.*?)       # all text before the date
  12.                        ((0|1)?\d)-        # one or two digits for the month
  13.                        ((0|1|2|3)?\d)-    # one or two digitas for the day
  14.                        ((19|20)\d\d)      # four digits for the year
  15.                        (.*?)$             # all text after the date
  16.                        ''', re.VERBOSE)
  17.  
  18. # Loop over the files in the working directory.
  19. for amerFilename in os.listdir(destFolder):
  20.     print(amerFilename)
  21.     mo = datePattern.search(amerFilename)
  22.     #print(mo.group(0))
  23.     # Skip files without a date.
  24.     if mo == None:
  25.         continue
  26.  
  27.     # Get the different parts of the filename.
  28.     beforePart = mo.group(1)
  29.     monthPart = mo.group(2)
  30.     dayPart = mo.group(4)
  31.     yearPart = mo.group(6)
  32.     afterPart = mo.group(8)
  33.  
  34.     # Form the European-style filename.
  35.     euroFilename = beforePart + \
  36.                    dayPart + '-' + monthPart + '-' + yearPart + \
  37.                    afterPart
  38.  
  39.     # Get the full, absolute file paths.
  40.     absWorkingDir = os.path.abspath(destFolder)
  41.     amerFilename = os.path.join(absWorkingDir, amerFilename)
  42.     euroFilename = os.path.join(absWorkingDir, euroFilename)
  43.  
  44.     # Rename the files.
  45.     print('Renameing "%s" to "%s"...' % (amerFilename, euroFilename))
  46.     shutil.move(amerFilename, euroFilename) # uncomment after testing
  47.  
  48. print('Finished.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement