Read Value from Config File Python

穿精又带淫゛_ 提交于 2021-02-08 15:22:00

问题


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

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


I would have use

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

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 =.

I'm kind of stuck here :

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 ?


回答1:


Have a look at the config parser: https://docs.python.org/3/library/configparser.html

It's more elegant than a self-made solution




回答2:


Modify your .env to

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

Python code

#!/usr/local/bin/python
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('test.env')
print config.get('DB','DB_DATABASE')

Output:

bheng-local




回答3:


This should work for you

#!/usr/local/bin/python
file = open('test.env', "r")
read = file.read()

for line in read.splitlines():
    if 'DB_DATABASE=' in line:
        print line.split('=',1)[1]



回答4:


#!/usr/local/bin/python

from configobj import ConfigObj
conf = ConfigObj('test.env')
print conf['DB_DATABASE']


来源:https://stackoverflow.com/questions/42568084/read-value-from-config-file-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!