標籤:python Regex ascii os
Regexre模組中用findall尋找到的是ascii碼,所以當比對替換時也需要對應的ascii碼才能匹配成功。以下程式是尋找檔案夾下檔案名稱中含有男、女的檔案,並將男替換成1,將女替換成2的程式
# -*- coding: utf-8 -*- import fnmatchimport osimport codecsimport reimport 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()
python中re.findall()找到的結果替換