Python实现小功能--替换文件中某个字符串

直接使用configparser对ini文件进行修改后,注释信息会丢失。所以曲线救国,写一个小功能,通过替换文件中的字符串,修改ini配置文件中的字段取值,注释信息就会保留住。

代码如下:

# 替换test.ini文件中的option=1字符串为option=0
class FileUtil:
    def alter(self, file, old_str, new_str, encode='UTF-8'):
        """
        替换文件中的字符串
        :param file:文件名
        :param old_str:就字符串
        :param new_str:新字符串
        :return:
        """
        file_data = ""
        with open(file, "r", encoding=encode) as f:
            for line in f:
                if old_str in line:
                    line = line.replace(old_str,new_str)
                file_data += line
        with open(file, "w", encoding=encode) as f:
            f.write(file_data)
    
    # 判断修改后的新字符串在文件中是否存在
    def new_str_exist(self, file, new_str):
        with open(file, "r", encoding=encode) as f:
            for line in f:
              
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值