简体   繁体   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"
   

How I can change a value of parameter in line.我如何在线更改参数值。

Just to be clear, you open a config file (may we have a example of the structure? If it is a JSON file or similar, it could be easier), loop trough all lines of it and want to change one line?明确一点,您打开一个配置文件(我们可以举一个结构示例吗?如果它是一个 JSON 文件或类似文件,它可能会更容易),遍历它的所有行并想要更改一行?

The best way would be to recreate the file, stocked in a string and then rewrite it.最好的方法是重新创建文件,存储在一个字符串中,然后重写它。

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

EDIT: with your comment QA Answser, I'ld go with:编辑:根据您的评论 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