Python batch file name modification implementation code

  • 2020-04-02 14:02:03
  • OfStack

#coding:utf-8 
# Batch file name modification  
import os import re import datetime 
 
re_st = r'(d+)+s?((d+))'
 # Used to match old file names , Grouping is required  re_match_old_file_name = re.compile(re_st) 
 # Directory to modify  WORKING_PATH = r'F:Gallery'
 
 #---------------------------------------------------------------------- 
def rename_fomat(name): 
  """ 
   File renaming formats organize modules ( General modification here is ok ) 
  NOTE: The return type must be unicode 
  """
  if name: 
    re_rn = re_match_old_file_name.findall(name) 
    if re_rn and re_rn != []: 
      re_rn = re_rn[0] 
      num = int(re_rn) 
      new_nm = u'NO.%04d' % ( num) 
      return new_nm 
 #---------------------------------------------------------------------- 
def logs(error): 
  """ 
   Error logging  
  """
  log = '' 
  LOG_FILE = open(r'./log.txt', 'a') 
  live_info =""" 
========== 
Time : %s 
title : %s 
Path : 
%s 
========== 
""" % ( 
    datetime.datetime.now(), 
    str(error['title']), 
    str(error['index']), 
  ) 
  log += live_info 
  errors = error['error_paths'] 
  for item in errors: 
    item = '%sn' % item 
    log += item 
  log = log.encode('utf-8') 
  try: 
    LOG_FILE.write(log) 
  except IOError: 
    print u' Write log failure '
  finally: 
    LOG_FILE.close() 
 #---------------------------------------------------------------------- 
def rename(old, new): 
  """ 
   File rename module  
  return: 
    0:rename success 
    1:the new path is exists 
    -1:rename failed 
  """
  if not os.path.exists(new): 
    try: 
      os.renames(old, new) 
      return 0
    except IOError: 
      print 'path error:', new 
      return -1
  else: 
    return 1
 #---------------------------------------------------------------------- 
def get_dirs(path): 
  """ 
   Get directory list  
  """
  if os.path.exists(path): 
    return os.listdir(path) 
  else: 
    return -1
 
 #---------------------------------------------------------------------- 
def get_input_result(word, choice): 
  """ 
   Get the correct input result  
  """
  correct_result = set(choice) 
  word = '===%s?n[in]:' % (word) 
  while True: 
    in_choice = raw_input(word) 
    if in_choice in correct_result: return in_choice 
   
 
 #---------------------------------------------------------------------- 
def batch_rename(index, dirs = []): 
  """ 
   Batch modification file  
  """
  index = unicode(index) 
  errors = [] 
  if dirs == []: 
    dirs = get_dirs(path = index) 
  if dirs and dirs != []: 
    for item in dirs: 
      item = unicode(item) 
      new_name = rename_fomat(item) 
      if new_name : 
        old_pt = u'%s\%s'% (index, item) 
        new_pt = u'%s\%s'% (index, new_name) 
        res_rn = rename(old_pt, new_pt) 
        if res_rn != 0: 
          errors.append(item) 
      else: 
        errors.append(item) 
    if errors and errors != []: 
      print 'Rename Failed:'
      logs({ 
        'index': index, 
        'title': 'Rename Failed' , 
        'error_paths': errors, 
      }) 
      for i, item in enumerate(errors): 
        print item, '|', 
        if i % 5 == 4: 
          print '' 
      print '' 
  else: 
    return -1
 #---------------------------------------------------------------------- 
def batch_rename_test(index): 
  """ 
   test  
   Return filter results  
  """
  index = unicode(index) 
  errors = [] 
  correct = [] 
  dirs = get_dirs(path = index) 
  if dirs and dirs != []: 
    for x, item in enumerate(dirs): 
      item = unicode(item) 
      new_name = rename_fomat(item) 
      if new_name : 
        correct.append(item) 
        old_pt = u'%s\%s'% (index, item) 
        new_pt = u'%s\%s'% (index, new_name) 
        print '[%d]O: %s' % ( x + 1, old_pt) 
        print '[%d]N: %s' % ( x + 1, new_pt) 
      else: 
        errors.append(item) 
    if errors and errors != []: 
      print 'Not Match:'
      logs({ 
        'index': index, 
        'title': 'Not Match', 
        'error_paths': errors, 
      }) 
      for i, item in enumerate(errors): 
        print item, '|', 
        if i % 5 == 4: 
          print '' 
      print '' 
  return correct 
   #---------------------------------------------------------------------- 
def manage(index): 
  """ 
   Program organization block  
  """
  file_filter = batch_rename_test(index) 
  do_choice = get_input_result( 
    word = 'Do with this(y / n)', 
    choice = ['y', 'n'] 
  ) 
  if do_choice == 'y': 
    batch_rename(index, dirs= file_filter) 
  print 'Finished !'
 
 if __name__ == '__main__': 
  path = WORKING_PATH 
  manage(index = path)

Related articles: