首页 > 代码库 > python的N个小功能(文件内容的匹配替换)

python的N个小功能(文件内容的匹配替换)

# -*- coding: utf-8 -*-

"""

Created on Fri Feb 17 20:25:05 2017

 

@author: who

"""

 

 

import os

import os.path

import re

 

import string

 

rootdir=r‘D:\test‘

 

for parent, dirnames, filenames in os.walk(rootdir):   # 三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字

 

 

    try:

        for filename in filenames:

 

            filenamepre=os.path.splitext(filename.decode("gbk"))[0];#文件名前缀

            filetype=os.path.splitext(filename.decode("gbk"))[1].lower();#文件扩展名

 

            pswpath = os.path.join(parent, filename.decode("gbk"));

            tmppath = os.path.join(r‘D:\testxx‘,filename.decode("gbk")) #写到另一个文件夹#

            if filetype==‘.txt‘:

                a=string.find(filenamepre,‘9999‘)                      ####符合类型的文件####

                if a==0:

                    tmp_file = open(tmppath, "w")

                    with open(pswpath) as f:

                        lines = f.readlines()            

 

                        for line in lines:                  ####一行一行读取 ####  

                            if line.find(‘aaa‘) > -1:         ####找到含aaa有的这行,匹配出对应整数数字####

                                m=re.compile(‘aaa([0-9]+)‘)

                                ms=m.search(line)

                                print ms.group(1)

                                line.replace(ms.group(1),filenamepre)   ####进行替换

                                tmp_file.write(line.replace(ms.group(1),filenamepre))  ###写出替换的该行

                            else:

                                tmp_file.write(line)

                     

                    tmp_file.close()

                else:

                    tmp_file = open(tmppath, "w")

                    with open(pswpath) as f:

                        lines = f.readlines()            

 

                        for line in lines:                  ####一行一行读取 ####  

                            tmp_file.write(line)

 

                    tmp_file.close()

               

           

    except IOError:

        pass

python的N个小功能(文件内容的匹配替换)