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


Posted in Python onSeptember 01, 2014
#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)
Python 相关文章推荐
Python下的subprocess模块的入门指引
Apr 16 Python
在Docker上开始部署Python应用的教程
Apr 17 Python
Python基础学习之常见的内建函数整理
Sep 06 Python
Python WXPY实现微信监控报警功能的代码
Oct 20 Python
Python基础练习之用户登录实现代码分享
Nov 08 Python
遗传算法python版
Mar 19 Python
pybind11在Windows下的使用教程
Jul 04 Python
用Python实现将一张图片分成9宫格的示例
Jul 05 Python
Django实现跨域的2种方法
Jul 31 Python
Python Web程序搭建简单的Web服务器
Jul 31 Python
Django模板标签{% for %}循环,获取制定条数据实例
May 14 Python
浅谈Python中文件夹和python package包的区别
Jun 01 Python
python中List的sort方法指南
Sep 01 #Python
Python抓取京东图书评论数据
Aug 31 #Python
Python深入学习之内存管理
Aug 31 #Python
Python深入学习之装饰器
Aug 31 #Python
Python深入学习之闭包
Aug 31 #Python
Python深入学习之对象的属性
Aug 31 #Python
Python深入学习之上下文管理器
Aug 31 #Python
You might like
PHP安装攻略:常见问题解答(一)
2006/10/09 PHP
PHP中simplexml_load_string函数使用说明
2011/01/01 PHP
PHP设计模式之装饰器模式定义与用法详解
2018/04/02 PHP
Firefox 无法获取cssRules 的解决办法
2006/10/11 Javascript
sina的lightbox效果。
2007/01/09 Javascript
iframe的onload在Chrome/Opera中执行两次Bug的解决方法
2011/03/17 Javascript
JavaScript高级程序设计 错误处理与调试学习笔记
2011/09/10 Javascript
js判断字符长度以及中英文数字等
2013/12/31 Javascript
jquery用offset()方法获得元素的xy坐标
2014/09/06 Javascript
实现placeholder效果的方案汇总
2015/06/11 Javascript
javascript html实现网页版日历代码
2016/03/08 Javascript
教你用javascript实现随机标签云效果_附代码
2016/03/16 Javascript
JavaScript中原型链存在的问题解析
2016/09/25 Javascript
js阻止移动端页面滚动的两种方法
2017/01/25 Javascript
Less 安装及基本用法
2018/05/05 Javascript
vue实现todolist基本功能以及数据存储功能实例详解
2019/04/11 Javascript
原生js实现俄罗斯方块
2020/10/20 Javascript
[47:20]DAC2018 4.4 淘汰赛 Optic vs Mineski 第一场
2018/04/05 DOTA
[01:32:22]DOTA2-DPC中国联赛 正赛 Ehome vs VG BO3 第一场 2月5日
2021/03/11 DOTA
Python实现拼接多张图片的方法
2014/12/01 Python
对python requests的content和text方法的区别详解
2018/10/11 Python
Pycharm连接远程服务器过程图解
2020/04/30 Python
完美解决jupyter由于无法import新包的问题
2020/05/26 Python
Python faker生成器生成虚拟数据代码实例
2020/07/20 Python
python中uuid模块实例浅析
2020/12/29 Python
Python3爬虫ChromeDriver的安装实例
2021/02/06 Python
澳大利亚制造的羊皮靴:Original UGG Boots
2017/11/13 全球购物
德国运动鞋网上商店:Afew Store
2018/01/05 全球购物
Lyle & Scott苏格兰金鹰官网:英国皇室御用品牌
2018/05/09 全球购物
美国在线纱线商店:Darn Good Yarn
2019/03/20 全球购物
2013年办公室秘书的个人自我鉴定
2013/10/24 职场文书
《大作家的小老师》教学反思
2014/04/16 职场文书
机关驾驶员违规检讨书
2014/09/13 职场文书
人事聘任通知
2015/04/21 职场文书
研讨会致辞
2015/07/31 职场文书
总经理聘用协议书
2015/09/21 职场文书