背景:
在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],如果原文件不存在则会产生该错误