windows下基于python中的rename进行批量重命名

背景:

在windows下对文件进行批量重命令。
注意其中的字符编码,由于windows是gbk的编码风格,一定要注意转换,否则会找不到文件的。

代码:

# -*- coding: cp936 -*-
__author__ = 'jason'
'''
通过提取出的文件名,正则表达式的方式提取出32位的hash
'''

hash_reg = r'(\w{32})'
import os, sys
import re
from nt import chdir
path = "E:\\yinyishell"
def listdir(dir, file):
    fielnum = 0
    list = os.listdir(dir)#列出目录下的所有文件和目录,方式1
    print 'all num=',len(list)
    for line in list:
        line = line.decode('gbk').encode('utf-8')#对非英文字符处理
        print line
        myhash = re.findall(hash_reg, line)
        new_hash = myhash[0]
        if len(new_hash) !=32:
            print 'error %s' % (new_hash)
        else:
            myfile.write(new_hash + '\n')
            fielnum = fielnum + 1
            #对文件进行rename
            line = line.decode('utf-8').encode('cp936')#注意这里!!
            name1 = "E:/yinyishell/krc/"+line
            new_hash = new_hash.decode('utf-8').encode('gb2312')
            name2 = "E:/yinyishell/krc/"+new_hash+".krc"            
            print 'old name=%s,new name=%s' % (name1,name2)
            try:
                os.rename(name1,name2)
            except Exception, e:
                print(e)
                continue
    myfile.write('all the file num is '+ str(fielnum))

resultfile = 'list.txt'
myfile = open(resultfile, 'w')
mydir = 'E:\\yinyishell\\krc'
listdir(mydir,myfile)
myfile.close()
#[WinError 123] 路径中存在非法字符
#[Error 3],”系统找不到该路径”,需要用绝对路径
#[Error 2],如果原文件不存在则会产生该错误
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值