从配置文件Python读取值

2024-06-17 13:00:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


我会有用的

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

但有些人可能会改变cofigs的顺序,这就是为什么linecache不是我的选择。


我不知道如何只检查一些字符串是否匹配,而是检查整行,并获取=之后的值。

我有点困在这里:

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

有人能推我一下吗?


Tags: 文件envlocalhosthttphostreaddbmy
3条回答

这应该对你有用

#!/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]

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

它比自制的解决方案更优雅

将.env修改为

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

Python代码

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

输出:

bheng-local

相关问题 更多 >