Python文件字符串替换脚本

Python文件字符串替换脚本

前言

由于在工作中会遇到一些文件的处理问题或者其他可以使用脚本完成的工作,这个系列将记录一些我用到过的脚本

文件夹下所有文件替换某个字符串

有个需求,我们需要替换某个目录下,所有文件下面的某个字符串,我们采用python来制作这个脚本

精简模式

这个脚本将该脚本目录下,所有文件中的“souceStr”替换成用户输入的destStr,可以自己根据需要手动更改相关地方

#!/usr/bin/python
# -*- coding:utf8 -*-

import os
import re

def replace(path, souceStr, destStr):
	#读取目录下所有文件
	files = os.listdir(path)
	#遍历这些文件
	for f in files:
		#如果文件名等于该脚本的名字 不执行
		if f == os.path.basename(__file__):
			continue
		#如果文件是一个目录 执行递归
		elif os.path.isdir(path + '/' + f):
			replace(path+ '/' + f, souceStr, destStr)
		#否则 是一个文件
		else:
			filePath = path+'/'+f
			f=open(filePath,'r')
			#读出该文件所有的行
			alllines=f.readlines()
			f.close()
			f=open(filePath,'w+')
			#对所有的行进行循环
			for eachline in alllines:
				#替换字符串
				a=re.sub(souceStr,destStr,eachline)
				f.writelines(a)
			f.close()

replace('./', "souceStr", input("please input destStr, rember to add ' at the beginning and end :"))

详细模式

这个脚本和上一个脚本是一样的,只是添加了一些输出和隐藏文件夹的判断,可以根据需要更改相应变量

#!/usr/bin/python  
# -*- coding:utf8 -*-  
  
import os  
import re
totalFile = 0 
print os.path.basename(__file__) 
def replace(path,str1,str2):
    # 返回一个列表,其中包含在目录条目的名称(google翻译)  
    files = os.listdir(path)    
    for f in files:  
        if(os.path.isdir(path + '/' + f)):  
            # 排除隐藏文件夹。因为隐藏文件夹过多  
            if(f[0] == '.'):  
                pass  
            else:  
                # 进入下一层文件夹  
                replace(path+ '/' + f,str1,str2)  
        if(os.path.isfile(path + '/' + f)):
			filePath = path+'/'+f
			f=open(filePath,'r')
			alllines=f.readlines()
			f.close()
			f=open(filePath,'w+')
			for eachline in alllines:
				a=re.sub(str1,str2,eachline)
				f.writelines(a)
			print filePath+"-->>>"+str1+" replace "+str2+" success!"
			global totalFile
			totalFile = totalFile + 1
			f.close()
  
if __name__ == '__main__':
    replace('E:/python/test',"hi",input("input str(rember to add '' at the beginning and end):"))
    #输出执行文件的总数量
    print 'totalFile =', totalFile

去除文件中的注释和空白行

我们有一个需求,就是去掉某些文件中的注释或者是空白行

可以根据需要结合上面的脚本实现对某个目录下的所有文件去除注释和空白行

#!/usr/bin/python
# -*- coding:utf8 -*-

import os
import re

def replace(path):
	f=open(path,'r')
	alllines=f.readlines()
	f.close()
	f=open(path,'w+')
	for eachline in alllines:
		#去除首尾空格
		line = eachline.strip()
		if not len(line) or line.startswith('#'):
			continue
		else:
			f.writelines(eachline)
	f.close()

replace('E:/python/test/core.yaml')

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值