python 替换指定路径下的文件内容中的关键字(包括路径中的)


import os

class ReplaceFileKeywords:
    
    def __init__(self, template_path, old_keyword, new_keyword):
        self.template_path = template_path
        self.old_keyword = old_keyword
        self.new_keyword = new_keyword

    def replaceContentKeywords(self, content=''):

        content = content if content else self.template_path
        old_keyword = self.old_keyword
        new_keyword = self.new_keyword

        return content.replace(old_keyword, new_keyword)\
            .replace(old_keyword.capitalize(), new_keyword.capitalize())\
            .replace(old_keyword.upper(), new_keyword.upper())


    def handlePath(self, template_path=''):
        # test_path = 'E:\phpStudy\WWW\local.python.com\HelloWorld'
        template_path = template_path if template_path else self.template_path

        new_payment_path = self.replaceContentKeywords(template_path)

        if not os.path.isdir(new_payment_path):
            os.makedirs(new_payment_path)
            
        for filename in os.listdir(template_path):
            cur_path = template_path + '/' + filename
            if os.path.isdir(cur_path):

                # print('-'*20)
                # print(cur_path, 'is dir.')

                self.handlePath(cur_path)

            else:

                file_handle = open(cur_path, 'r')
                new_file = new_payment_path + '/' + self.replaceContentKeywords(filename)
                
                with open(cur_path, 'r') as file_handle:
                    file_content = file_handle.read()
                    new_content = self.replaceContentKeywords(file_content)

                    with open(new_file, 'w') as new_file_handle:
                        new_file_handle.write(new_content)

                # print(cur_path, 'is file')

template_path = 'E:\phpStudy\WWW\local.python.com\payment\stripe'
old_payment_keyword = 'stripe'
new_payment_keyword = 'yipay'

obj = ReplaceFileKeywords(template_path, old_payment_keyword, new_payment_keyword)
obj.handlePath()

# handlePath(template_path, old_payment_keyword, new_payment_keyword)

print('finish')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值