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 23 Python
python统计文本字符串里单词出现频率的方法
May 26 Python
常见python正则用法的简单实例
Jun 21 Python
wxPython的安装与使用教程
Aug 31 Python
python读取txt文件中特定位置字符的方法
Dec 24 Python
对PyQt5基本窗口控件 QMainWindow的使用详解
Jun 19 Python
Python如何基于rsa模块实现非对称加密与解密
Jan 03 Python
浅谈Django QuerySet对象(模型.objects)的常用方法
Mar 28 Python
django中嵌套的try-except实例
May 21 Python
python合并多个excel文件的示例
Sep 23 Python
Python使用永中文档转换服务
May 06 Python
Python TypeError: ‘float‘ object is not subscriptable错误解决
Dec 24 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/07/09 PHP
深入PHP FTP类的详解
2013/06/13 PHP
php实现在多维数组中查找特定value的方法
2015/07/29 PHP
php实现支持中文的文件下载功能示例
2017/08/30 PHP
php中pcntl_fork创建子进程的方法实例
2019/03/14 PHP
JQuery Tab选项卡效果代码改进版
2010/04/01 Javascript
使用jquery实现放大镜效果
2014/09/02 Javascript
jquery中$.fn和图片滚动效果实现的必备知识总结
2017/04/21 jQuery
jQuery实现简单的抽奖游戏
2017/05/05 jQuery
React Native仿美团下拉菜单的实例代码
2017/08/08 Javascript
jQuery实现腾讯信用界面(自制刻度尺)样式
2017/08/15 jQuery
form表单序列化详解(推荐)
2017/08/15 Javascript
Angular简单验证功能示例
2017/12/22 Javascript
使用Ajax和Jquery配合数据库实现下拉框的二级联动的示例
2018/01/25 jQuery
记一次webpack3升级webpack4的踩坑经历
2018/06/12 Javascript
详解一个基于react+webpack的多页面应用配置
2019/01/21 Javascript
浅谈Angular单元测试总结
2019/03/22 Javascript
vue eslint简要配置教程详解
2019/07/26 Javascript
js 判断当前时间是否处于某个一个时间段内
2019/09/19 Javascript
js实现无缝轮播图
2020/03/09 Javascript
微信小程序使用GoEasy实现websocket实时通讯
2020/05/19 Javascript
解决微信授权成功后点击按返回键出现空白页和报错的问题
2020/06/08 Javascript
python中将阿拉伯数字转换成中文的实现代码
2011/05/19 Python
Python实现一个带权无回置随机抽选函数的方法
2019/07/24 Python
使用python实现飞机大战游戏
2020/03/23 Python
Python中lru_cache的使用和实现详解
2021/01/25 Python
IE支持HTML5的解决方法
2009/10/20 HTML / CSS
html5 Canvas绘制线条 closePath()实例代码
2012/05/10 HTML / CSS
Wedgwood美国官网:英国骨瓷,精美礼品及家居装饰
2018/02/17 全球购物
市场开发计划书
2014/05/07 职场文书
个人作风建设剖析材料
2014/10/11 职场文书
城南旧事电影观后感
2015/06/16 职场文书
2016入党积极分子党课培训心得体会
2016/01/06 职场文书
《悲惨世界》:比天空更广阔的是人的心灵
2020/01/16 职场文书
Python进阶学习之带你探寻Python类的鼻祖-元类
2021/05/08 Python
Python使用socket去实现TCP客户端和TCP服务端
2022/04/12 Python