Python-dotenv could not parse statement starting at line 2

Viewed 25416

Python-dotenv could not parse statement starting at line 2

I have uninstalled and reinstalled python-dotenv still i get same error. Could anyone sort this?

6 Answers

Make sure your .env file only contains data in the following format:

MY_ENV_VAR = value

Anything other than this and you will get NoneType if you are trying to retrieve them.

When you are trying to retrieve these you can do the following:

from pathlib import Path
from dotenv import load_dotenv

env_path = Path('.', '.env')
load_dotenv(dotenv_path=env_path)

my_env_var = os.getenv('MY_ENV_VAR')

The env_path is simply the path to your .env file. The '.' is the root directory of your app. You can even pass it in the dotenv_path argument like '\path\to\your\.env' e.g. load_dotenv(dotenv_path='\path\to\your\.env').

EDIT:

If you are adding it in your terminal, make sure there is no whitespace around the = sign. For instance:

Linux:

$ export MY_ENV_VAR=value

Windows:

> set MY_ENV_VAR=value 

For me the problem disappeared when I deleted space after equality sign and removed apostrophes (') and quotation marks (") from my .env file. So instead of this .env:

FOO = 'something'
BAR = "something_else"

Try changing .env to:

FOO=something
BAR=something_else

In my case, that was not the issue, even I had empty lines at the end. The culprit was a breaking strict rules line copied from a Dockerfile

ENV VAR=value

The python env, and env files are restrictive to just a name identifier with underscores, an equal and all to the left is taken as the value for the identifier. "ENV " part was breaking that strict rule...

It need to be just VAR=value

While some time ago, hope this help others

Not Sure What the exact reason is. I also had the same problem. If I remember correctly, the problem arised in my case after pasting the var=value pair in the .env file using vim.

Removing var=value with backspace, and manually typing var=value (without pasting) workded for me.*

I had this same error when the comment in my .env file started with ;

My Visual Studio Code for some reason comments out the lines with ; in place of # in .env files

So to fix the error I only had to replace from ; with # in my commented lines

Related