How would I make my .env file work in my .py file?

Making a discord bot and I want to store variables in a .env file.

It throws this exception:

  File "c:UsersAdamDocumentsDiscordBotmain.py", line 24, in <module>
    client.run(TOKEN)
  File "C:UsersAdamAppDataLocalProgramsPythonPython39libsite-packagesdiscordclient.py", line 723, in run
    return future.result()
  File "C:UsersAdamAppDataLocalProgramsPythonPython39libsite-packagesdiscordclient.py", line 702, in runner
    await self.start(*args, **kwargs)
  File "C:UsersAdamAppDataLocalProgramsPythonPython39libsite-packagesdiscordclient.py", line 665, in start
    await self.login(*args, bot=bot)
  File "C:UsersAdamAppDataLocalProgramsPythonPython39libsite-packagesdiscordclient.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'

Before I moved the variables to the .env file it worked fine.

#.py
import os

from dotenv import load_dotenv
import discord

load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("GUILD_NAME")

client = discord.Client()


@client.event
async def on_ready():
    for guild in client.guilds:
        if guild.name == GUILD:
            break

    print(
        f"{client.user} is connected to the following guild:n"
        f"{guild.name}(id: {guild.id}"
    )

client.run(TOKEN)

#.env
DISCORD_TOKEN=my_discord_token
GUILD_NAME=Testing

My .env and .py are in the same folder.

Answer

python-dotenv‘s load_env() searches for a .env file in the same directory as where it’s being executed.
If you change your .env filename to a custom one, like var.env, you must specify the filename: load_env("var.env")