码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-02-25 21:15:23      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:bsp   扩展名   walk   gbk   close   nbsp   os.walk   wpa   lower   

# -*- 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个小功能(文件内容的匹配替换)

标签:bsp   扩展名   walk   gbk   close   nbsp   os.walk   wpa   lower   

原文地址:http://www.cnblogs.com/dudumiaomiao/p/6442684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!