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