首页 > 解决方案 > 如何更改配置文件python行中的值

问题描述

file = open("my_config", "r")
for line in file:
    change line to "new_line"
   

如何在线更改参数的值。

标签: pythonparametersconfig

解决方案


为了清楚起见,您打开一个配置文件(我们可以提供一个结构示例吗?如果是 JSON 文件或类似文件,可能会更容易),遍历它的所有行并想要更改一行?

最好的方法是重新创建文件,存储在一个字符串中,然后重写它。

file = open("my_config", "w")
str_file = ""
for line in file:
    # Change the line here
    str_file += line+'\n'

str_file = str_file.strip() #To remove the last \n

file.write(str_file)
file.close()

编辑:根据您的评论 QA Answser,我会选择:

file = open("my_config", "w")
str_file = ""
for line in file:
    if (line.split(':')[0] == 'SECURITY_LEVEL'):
        line = 'SECURITY_LEVEL:' + VALUE #your new value here
    str_file += line+'\n'

str_file = str_file.strip() #To remove the last \n

file.write(str_file)
file.close()

推荐阅读