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实现扫描指定目录下的子目录及文件的方法
Jul 16 Python
python开发中module模块用法实例分析
Nov 12 Python
深入理解Python单元测试unittest的使用示例
Nov 18 Python
Python的log日志功能及设置方法
Jul 11 Python
python join方法使用详解
Jul 30 Python
python爬虫豆瓣网的模拟登录实现
Aug 21 Python
python3.5 cv2 获取视频特定帧生成jpg图片
Aug 28 Python
tensorflow 限制显存大小的实现
Feb 03 Python
Python多线程threading join和守护线程setDeamon原理详解
Mar 18 Python
Python实现播放和录制声音的功能
Aug 12 Python
Python tkinter之ComboBox(下拉框)的使用简介
Feb 05 Python
python脚本框架webpy模板控制结构
Nov 20 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面向对象全攻略 (一) 面向对象基础知识
2009/09/30 PHP
PHP实现把数字ID转字母ID
2013/08/12 PHP
PHP简单获取网站百度搜索和搜狗搜索收录量的方法
2016/08/23 PHP
JavaScript 基础知识 被自己遗忘的
2009/10/15 Javascript
通过javascript获取iframe里的值示例代码
2013/06/24 Javascript
解决js数据包含加号+通过ajax传到后台时出现连接错误
2013/08/01 Javascript
JS中引用百度地图并将百度地图的logo和信息去掉
2013/09/29 Javascript
21个JavaScript事件(Events)属性汇总
2014/12/02 Javascript
jQuery.Highcharts.js绘制柱状图饼状图曲线图
2015/03/14 Javascript
JavaScript中使用concat()方法拼接字符串的教程
2015/06/06 Javascript
javascript实现列表滚动的方法
2015/07/30 Javascript
多种jQuery绑定事件的实现方式
2016/06/13 Javascript
windows下vue-cli及webpack搭建安装环境
2017/04/25 Javascript
JS实现多物体运动的方法详解
2018/01/23 Javascript
webpack将js打包后的map文件详解
2018/02/22 Javascript
js+css实现红包雨效果
2018/07/12 Javascript
用Cordova打包Vue项目的方法步骤
2019/02/02 Javascript
react配置antd按需加载的使用
2019/02/11 Javascript
Python中if __name__ == "__main__"详细解释
2014/10/21 Python
Python随机数用法实例详解【基于random模块】
2017/04/18 Python
python 字典中文key处理,读取,比较方法
2018/07/06 Python
python 遍历目录(包括子目录)下所有文件的实例
2018/07/11 Python
浅谈python写入大量文件的问题
2018/11/09 Python
Windows下PyCharm2018.3.2 安装教程(图文详解)
2019/10/24 Python
Python requests模块安装及使用教程图解
2020/06/30 Python
Python基于execjs运行js过程解析
2020/11/27 Python
英国乐购杂货:Tesco Groceries
2018/11/29 全球购物
植村秀加拿大官网:Shu Uemura加拿大
2019/09/03 全球购物
师生聚会感言
2014/01/26 职场文书
机械专业求职信
2014/05/25 职场文书
趣味运动会策划方案
2014/06/02 职场文书
单位一把手群众路线四风问题整改措施
2014/09/25 职场文书
党的群众路线教育实践活动党员个人整改措施
2014/10/27 职场文书
听证通知书
2015/04/24 职场文书
工作自我评价范文
2019/03/21 职场文书
Go gorilla securecookie库的安装使用详解
2022/08/14 Golang