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("文件修改完成,请检查!")

猜你喜欢

转载自blog.csdn.net/nikeylee/article/details/123182586
今日推荐