Skip to content

Instantly share code, notes, and snippets.

@plembo
Last active May 4, 2023 23:16
Show Gist options
  • Select an option

  • Save plembo/2289ef51b6c00f00b547e78a43fafcb6 to your computer and use it in GitHub Desktop.

Select an option

Save plembo/2289ef51b6c00f00b547e78a43fafcb6 to your computer and use it in GitHub Desktop.
Python reading .env file

Reading a .env file in Python

The os.environ.get method is usually what I used to read configuration information in the system environment, including secrets, in my python scripts. But sometimes (like during testing) it's convenient to use a local file instead. That's where the python-dotenv library comes in handy.

The library leverages os.environ.get to load variables from a .env file like the system loads them from .profile or .bashrc (in Unix-like systems). By default dotenv looks for the .env file in the same directory as the running program. Note: Always remmember to exclude it from your repo by adding ".env" to your .gitignore. Github's own sample Python.gitignore already does that.

Install:

$ pip install python-dotenv --user

Import and use:

import os
from dotenv import load_dotenv
load_dotenv()

client_id = os.getenv('CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET')

Where the .env file looks something like this:

CLIENT_ID="xxxxxxxx"
CLIENT_SECRET="xxxxxxxx"

Note that you have to import both os and dotenv.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment