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爬虫教程之爬取百度贴吧并下载的示例
Mar 07 Python
跟老齐学Python之编写类之四再论继承
Oct 11 Python
python制作一个桌面便签软件
Aug 09 Python
python中通过预先编译正则表达式提高效率
Sep 25 Python
python利用正则表达式排除集合中字符的功能示例
Oct 10 Python
python利用rsa库做公钥解密的方法教程
Dec 10 Python
python实现基于信息增益的决策树归纳
Dec 18 Python
django的settings中设置中文支持的实现
Apr 28 Python
使用pandas实现连续数据的离散化处理方式(分箱操作)
Nov 22 Python
Python二次规划和线性规划使用实例
Dec 09 Python
Python 如何展开嵌套的序列
Aug 01 Python
Python实现给PDF添加水印的方法
Jan 25 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中使用CURL模拟登录并获取数据实例
2014/07/01 PHP
php实现的任意进制互转类分享
2015/07/07 PHP
使用ThinkPHP的自动完成实现无限级分类实例详解
2016/09/02 PHP
简述php环境搭建与配置
2016/12/05 PHP
php面向对象基础详解【星际争霸游戏案例】
2020/01/23 PHP
php中get_object_vars()在数组的实例用法
2021/02/22 PHP
javaScript实现滚动新闻的方法
2015/07/30 Javascript
javascript轮播图算法
2016/10/21 Javascript
JQuery.validationEngine表单验证插件(推荐)
2016/12/10 Javascript
JS实现移动端实时监听输入框变化的实例代码
2017/04/12 Javascript
angularjs2中父子组件的数据传递的实例代码
2017/07/05 Javascript
微信小程序防止多次点击跳转(函数节流)
2019/09/19 Javascript
vue接口请求加密实例
2020/08/11 Javascript
node.js通过Sequelize 连接MySQL的方法
2020/12/28 Javascript
[02:30]联想杯DOTA2完美世界全国高校联赛—北京站现场
2015/11/16 DOTA
[03:54]Ehome出征西雅图 回顾2016国际邀请赛晋级之路
2016/08/02 DOTA
python实现通过shelve修改对象实例
2014/09/26 Python
python 基础教程之Map使用方法
2017/01/17 Python
python字符串中的单双引
2017/02/16 Python
python基础教程项目三之万能的XML
2018/04/02 Python
python序列化与数据持久化实例详解
2019/12/20 Python
使用python实现希尔、计数、基数基础排序的代码
2019/12/25 Python
基于python实现查询ip地址来源
2020/06/02 Python
html5视频自动横过来自适应页面且点击播放功能的实现
2020/06/03 HTML / CSS
世界上最好的精品店:Shoptiques
2018/02/05 全球购物
应届毕业生应聘自荐信
2013/12/07 职场文书
欢送退休感言
2014/02/08 职场文书
干部下基层实施方案
2014/03/14 职场文书
班委竞选演讲稿
2014/04/28 职场文书
农村党员对照检查材料
2014/09/24 职场文书
十二生肖观后感
2015/06/12 职场文书
让文件路径提取变得更简单的Python Path库
2021/05/27 Python
Apache SeaTunnel实现 非CDC数据抽取
2022/05/20 Servers
SpringCloud超详细讲解Feign声明式服务调用
2022/06/21 Java/Android
MySQL性能指标TPS+QPS+IOPS压测
2022/08/05 MySQL
js 实现Material UI点击涟漪效果示例
2022/09/23 Javascript