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:
                if new_str in line:
                    return True
        return False

util = FileUtil()

if __name__ == '__main__':
    encode = 'gbk'
    setup_path = r'D:\工具'
    file_list = [r'\Data\test.ini', r'\Caches\Data\test.ini']

    old_str = 'option=1'
    new_str = 'option=0'

    for file in file_list:
        file_path = setup_path + file
        util.alter(file_path, old_str, new_str, encode)
        result = util.new_str_exist(file_path, new_str)
        if(result):
            print(new_str + "   在文件中存在。  " + file_path)
        else:
            print(new_str + "   在文件中不存在!!!  " + file_path)
    print("文件修改完成,请检查!")

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值