直接使用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: