python替换内容_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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值