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

Posted 嘟嘟_猪

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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个小功能(文件内容的匹配替换)的主要内容,如果未能解决你的问题,请参考以下文章

python的N个小功能(更新文件)

电脑系统批处理,如何将多个tab替换为一个tab,而单个的tab不变化?

linux几种常见的文件内容查找和替换命令

nodejs 匹配字符串问题

python的文件操作读取内容替换

python 文件内容修改替换操作