首页 > 解决方案 > 如何在 Python 程序中读取(仅读取未设置).env 文件

问题描述

我有.env以下内容的文件:

DB_URL=''
DB_USER=''
DB_PASSWD=''
DB_NAME=''
COLLECTION_NAME=''

问题我想.env在我的 python 程序中读取这个文件来创建连接,mongodb但我只找到python了设置并使用模块env读取的库。os有没有办法只读取的内容.env

标签: pythonpython-3.xmongodb

解决方案


为什么不直接打开文件并自己解析呢?

import pathlib

def read_env(directory):
    env_path = pathlib.Path(directory) / '.env'
    d = {}
    with env_path.open('r') as f:
        for line in f:
            if '=' in line and not line.startswith('#'):  
                # 2nd check allows for files with commented lines, but if you
                # want to have keys starting with a literal '#', just have the 
                # 1st part of the if.
                key, value = line.split('=', 1)
                d[key] = value.strip("'")
    return d

推荐阅读