正则表达式re模块中用findall查找到的是ascii码,所以当比对替换时也需要对应的ascii码才能匹配成功。以下程序是查找文件夹下文件名中含有男、女的文件,并将男替换成1,将女替换成2的程序
# -*- coding: utf-8 -*- import fnmatch import os import codecs import re import sys def iterfindfiles(path, fnexp): for root, dirs, files in os.walk(path): for filename in fnmatch.filter(files, fnexp): yield os.path.join(root, filename) def fiterFiles(): path=raw_input("input dir:") filterfiletype=raw_input("input file filter type:") #quanjiao_2_banjiao(path) for filename in iterfindfiles(path,filterfiletype): SingerList=re.findall('\((..?)\)\.dat',filename) for SingerName in SingerList: if(SingerName=='\xc4\xd0'): SingerName='1' new_filename=re.sub('\((..?)\)\.dat','(1).dat',filename) print new_filename os.rename(filename,new_filename) #print SingerName elif(SingerName=='\xc5\xae'): SingerName='2' new_filename=re.sub('\((..?)\)\.dat','(2).dat',filename) print new_filename os.rename(filename,new_filename) def main(): fiterFiles() if __name__ == "__main__": main()
原文地址:http://blog.csdn.net/dannyoung/article/details/45875591