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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM