python - Renaming of files for a given pattern -


i need help. there folder "c:\temp" in folder formatted files "in_ + 7123456789.amr" necessary make renaming of files given pattern. "in_ name _ date-create _ phone number.amr" correspondingly, if file called "out_ + 7123456789.amr" result format "out_ name_date-create_phone number.amr"

the question how specify file name has been checked before os.rename , depending on file name use template

import os  path = "c:/temp"   i, filename in enumerate(os.listdir(path)):     os.chdir(path)     os.rename(filename, 'name'+str(i) +'.txt')     = i+1 

sorry none of examples consistent in question, still don't understand c:\temp contains...

well, assuming like:

>>> os.listdir(path) ['in_ + 7123456789.amr', 'out_ + 7123456789.amr'] 

the example:

import datetime import re import os  os.chdir(path) filename in os.listdir(path):     match = re.match(r'(in|out)_ \+ (\d+).amr', filename)     if match:         file_date = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)         destination = '%s_%s_%s_phone number.amr' % (             match.group(1), # either in or out             match.group(2),             file_date.strftime('%y%m%d%h%m%s'), # adjust format @ convenience         )          os.rename(filename, destination) 

will produce:

  • in_7123456789_20150721094227_phone number.amr
  • out_7123456789_20150721094227_phone number.amr

other files won't match re.match pattern , ignored.


Comments