从配置文件Python读取值 [英] Read Value from Config File Python

查看:80
本文介绍了从配置文件Python读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件 .env 文件包含5行

I have a file .env file contain 5 lines

DB_HOST=http://localhost/
DB_DATABASE=bheng-local
DB_USERNAME=root
DB_PASSWORD=1234567890
UNIX_SOCKET=/tmp/mysql.sock

我想编写python来获取 DB_DATABASE 的值我想要这个 bheng-local

I want to write python to grab the value of DB_DATABASE I want this bheng-local

我会用

import linecache
print linecache.getline('.env', 2)

但是有些人可能会更改cofig的顺序,这就是为什么行缓存不是我的选择.

But some people might change the order of the cofigs, that's why linecache is not my option.

我不确定如何只检查某些字符串匹配但要检查整行,并在 = 之后获取值.

I am not sure how to check for only some strings match but all the entire line, and grab the value after the =.

我有点卡在这里:

file = open('.env', "r")
read = file.read()
my_line = ""

for line in read.splitlines():
    if line == "DB_DATABASE=":
        my_line = line
        break
print my_line

有人可以在这里给我一点推动力吗?

Can someone please give me a little push here ?

推荐答案

看看配置解析器: https://docs.python.org/3/library/configparser.html

比自制解决方案更优雅

这篇关于从配置文件Python读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆