python - 如何更改配置文件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,我会选择:
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()
推荐阅读
- python - 我想用 lstm 抽象文本
- c++ - 如何在不依赖于操作系统的搜索路径或任何环境变量的情况下为 g++ 命令指定 ld.exe 的路径?
- excel - Excel:如何获取当前单元格下方具有值的行的值?
- java - Java 时间段(十进制月数)
- python - 如何在python中设置类的模拟实例变量?
- backup - 备份数据库运行进程 processDB = Process.Start("DBBackup.bat");
- firebase - Firebase 深层链接:无效的动态链接
- python - 如何使用硒处理分页和刮擦
- python - 将两行具有不同索引的数据框组合起来
- kubernetes - 使用 SR-IOV 隔离 pod 流量