• 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: est'

    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: estxx',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

  • 相关阅读:
    MIT 6.828 JOS学习笔记10. Lab 1 Part 3: The kernel
    Java基础知识点4:继承
    CentOS Installation
    超微主板创建RAID磁盘阵列
    MySQL查询语句
    Psql操作命令
    Let's Encrypt 免费 SSL 证书续期
    Linux系统禁用swap分区
    公共 NTP 服务器地址
    Postgresql配置
  • 原文地址:https://www.cnblogs.com/dudumiaomiao/p/6442684.html
Copyright © 2020-2023  润新知