with open 替换行操作

Python编程中遇到替换文档中指定行的值操作

1、获取文件内容
2、列表生成式,根据 \n 切割值
3、遍历列表,根据预定值判断是否在其中
4、替换值
5、写入

with open("config"), "r") as f:
    config_file_content = f.read()

config_file_content = [e for e in config_file_content.split('\n')]
for i in range(len(config_file_content)):
    if 'path_wd' in config_file_content[i]:
        config_file_content[i] = "path_wd = {}".format(
            os.path.dirname(model_path))
with open("config", "w+") as f:
    f.write('\n'.join(config_file_content))

你可能感兴趣的:(with open 替换行操作)