python批量修改文件名的实现代码

yipeiwu_com5年前Python基础
#coding:utf-8 
#批量修改文件名 
import os import re import datetime 
 
re_st = r'(\d+)\+\s?\((\d+)\)'
 #用于匹配旧的文件名,需含分组 re_match_old_file_name = re.compile(re_st) 
 #要修改的目录 WORKING_PATH = r'F:\Gallery'
 
 #---------------------------------------------------------------------- 
def rename_fomat(name): 
  """ 
  文件重命名格式组织模块(一般修改这里就可以了) 
  NOTE:返回类型必须是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): 
  """ 
  错误记录 
  """
  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 = '%s\n' % item 
    log += item 
  log = log.encode('utf-8') 
  try: 
    LOG_FILE.write(log) 
  except IOError: 
    print u'写入日志失败'
  finally: 
    LOG_FILE.close() 
 #---------------------------------------------------------------------- 
def rename(old, new): 
  """ 
  文件重命名模块 
  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): 
  """ 
  获取目录列表 
  """
  if os.path.exists(path): 
    return os.listdir(path) 
  else: 
    return -1
 
 #---------------------------------------------------------------------- 
def get_input_result(word, choice): 
  """ 
  获取正确的输入结果 
  """
  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 = []): 
  """ 
  批量修改文件 
  """
  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): 
  """ 
  测试 
  返回过滤结果 
  """
  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): 
  """ 
  程序组织块 
  """
  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)

相关文章

django中media媒体路径设置的步骤

django中media媒体路径设置的步骤

1、创建一个app02, 并在settings.py里面设置 2、在settings.py里面设置媒体文件保存的路径 from django.contrib import admi...

彻底搞懂Python字符编码

彻底搞懂Python字符编码

不论你是有着多年经验的 Python 老司机还是刚入门 Python 不久,你一定遇到过UnicodeEncodeError、UnicodeDecodeError 错误,每当遇到错误我们...

Python中如何使用if语句处理列表实例代码

Python中如何使用if语句处理列表实例代码

前言 每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。条件测试为...

对python列表里的字典元素去重方法详解

如下所示: def list_dict_duplicate_removal(): data_list = [{"a": "123", "b": "321"}, {"a": "12...

Python中的数据对象持久化存储模块pickle的使用示例

Python中可以使用 pickle 模块将对象转化为文件保存在磁盘上,在需要的时候再读取并还原。具体用法如下: pickle是Python库中常用的序列化工具,可以将内存对象以文本或二...