繁体   English   中英

如何更改配置文件 python 行中的值

[英]How to change a value in line of config file python

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

我如何在线更改参数值。

明确一点,您打开一个配置文件(我们可以举一个结构示例吗?如果它是一个 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,我将 go 与:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM