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远程登录代码
Apr 29 Python
Python脚本获取操作系统版本信息
Dec 17 Python
python中字符串类型json操作的注意事项
May 02 Python
Python读取和处理文件后缀为.sqlite的数据文件(实例讲解)
Jun 27 Python
python实现杨辉三角思路
Jul 14 Python
python下10个简单实例代码
Nov 15 Python
浅谈Django REST Framework限速
Dec 12 Python
python opencv之SIFT算法示例
Feb 24 Python
python使用wxpy实现微信消息防撤回脚本
Apr 29 Python
如何使用python爬虫爬取要登陆的网站
Jul 12 Python
如何基于python测量代码运行时间
Dec 25 Python
python中如何对多变量连续赋值
Jun 03 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基础学习笔记
2007/03/18 PHP
php+mysqli使用面向对象方式查询数据库实例
2015/01/29 PHP
老生常谈PHP面向对象之注册表模式
2017/05/26 PHP
PHP基于timestamp和nonce实现的防止重放攻击方案分析
2019/07/26 PHP
学习ExtJS Panel常用方法
2009/10/07 Javascript
JQuery中对服务器控件 DropdownList, RadioButtonList, CheckboxList的操作总结
2011/06/28 Javascript
jquery实现网页查找功能示例分享
2014/02/12 Javascript
jQuery实现大转盘抽奖活动仿QQ音乐代码分享
2015/08/21 Javascript
js验证手机号、密码、短信验证码代码工具类
2020/06/24 Javascript
Vue常用指令V-model用法
2017/03/08 Javascript
JS中使用gulp实现压缩文件及浏览器热加载功能
2017/07/12 Javascript
对于Javascript 执行上下文的全面了解
2017/09/05 Javascript
移动端网页开发调试神器Eruda的介绍与使用技巧
2017/10/30 Javascript
解决使用Vue.js显示数据的时,页面闪现原始代码的问题
2018/02/11 Javascript
基于vue-cli 路由 实现类似tab切换效果(vue 2.0)
2019/05/08 Javascript
eslint 的三大通用规则详解
2019/05/16 Javascript
JS使用new操作符创建对象的方法分析
2019/05/30 Javascript
浅谈layui里的上传控件问题
2019/09/26 Javascript
JS实现音乐导航特效
2020/01/06 Javascript
Vue实现开关按钮拖拽效果
2020/09/22 Javascript
[02:21]十步杀一人,千里不留行——DOTA2全新英雄天涯墨客展示
2018/08/29 DOTA
windows系统中python使用rar命令压缩多个文件夹示例
2014/05/06 Python
Python中使用socket发送HTTP请求数据接收不完整问题解决方法
2015/02/04 Python
python在ubuntu中的几种安装方法(小结)
2017/12/08 Python
python celery分布式任务队列的使用详解
2019/07/08 Python
python 的 scapy库,实现网卡收发包的例子
2019/07/23 Python
python找出列表中大于某个阈值的数据段示例
2019/11/24 Python
Python urllib request模块发送请求实现过程解析
2020/12/10 Python
网易微博Web App用HTML5开发的过程介绍
2012/06/13 HTML / CSS
英国女士和男士时尚服装网上购物:Top Labels Online
2018/03/25 全球购物
社团活动策划书范文
2014/01/09 职场文书
大一新生学期自我评价
2014/04/09 职场文书
社团活动总结范文
2014/04/26 职场文书
勤奋学习演讲稿
2014/05/10 职场文书
大学生年度个人总结
2015/02/15 职场文书
Rust 连接 PostgreSQL 数据库的详细过程
2022/01/22 PostgreSQL