Skip to content

Instantly share code, notes, and snippets.

@ayoubzulfiqar
Created June 12, 2025 17:56
Show Gist options
  • Save ayoubzulfiqar/297d8c0021523540ab50f9ea487bb98b to your computer and use it in GitHub Desktop.
Save ayoubzulfiqar/297d8c0021523540ab50f9ea487bb98b to your computer and use it in GitHub Desktop.
READ ENV

Put this at the top of the file inside .env

# .env

Function to read the file

encoding = locale.getpreferredencoding()


def LOADENV():
    try:
        with open(".env", "r", encoding=encoding) as f:
            for line in f:
                line = line.strip()
                
                if not line or line.startswith("#"):
                    continue
                
                key, value = line.split("=", 1)
                key = key.strip()
                value = value.strip()
               
                if value.startswith(('"', "'")) and value[0] == value[-1]:
                    value = value[1:-1]
                os.environ[key] = value
    except FileNotFoundError:
        print("Warning: Not found. Using system environment variables.")

then in main file whereever you wanna load

LOADENV()
key: str = os.getenv("STRING INSIDE THE ENV")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment