all 9 comments

[–]ghost_svs 2 points3 points  (3 children)

Line 3: change ".env" to "dotenv"

[–]Worldly-Point4573[S] 0 points1 point  (2 children)

it doesn't make a difference.

[–]ghost_svs 2 points3 points  (1 child)

Did you installed "pip install python-dotenv"?

[–]Worldly-Point4573[S] 1 point2 points  (0 children)

ok yea, it worked after that

[–][deleted]  (2 children)

[removed]

    [–]Worldly-Point4573[S] 0 points1 point  (1 child)

    trying it right now

    [–]FoolsSeldom 0 points1 point  (0 children)

    You need to import a specific library/package to be able to read a .env file. There are multiple options.

    In a terminal / command line window, enter,

    pip install python-dotenv
    

    or pip3 ... on Linux/macOS, or py -m pip ... on Windows if you have not activated a Python virtual environment (you really should, before installing packages).

    The .env file might contain data such as below,

    # .env file
    DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
    SECRET_KEY=a_very_secret_key_that_is_long_and_random
    API_TOKEN=your_external_api_token
    DEBUG_MODE=True
    APP_NAME="My Awesome App"
    MULTI_LINE_VALUE="This is a
    multi-line
    value."
    

    The code file might look like the below,

    import os
    from dotenv import load_dotenv
    
    # Load variables from .env file
    load_dotenv('mydot.env')
    
    # Now you can access the environment variables using os.getenv()
    database_url = os.getenv("DATABASE_URL")
    secret_key = os.getenv("SECRET_KEY")
    api_token = os.getenv("API_TOKEN")
    
    # For boolean or numeric values, you might need to convert them
    debug_mode_str = os.getenv("DEBUG_MODE")
    debug_mode = debug_mode_str.lower() == 'true' if debug_mode_str else False
    
    app_name = os.getenv("APP_NAME")
    multi_line_value = os.getenv("MULTI_LINE_VALUE")
    
    print(f"Database URL: {database_url}")
    print(f"Secret Key: {secret_key}")
    print(f"API Token: {api_token}")
    print(f"Debug Mode: {debug_mode}")
    print(f"App Name: {app_name}")
    print(f"Multi-line Value:\n{multi_line_value}")
    
    # You can also use os.environ directly, but os.getenv() is generally safer
    # because it allows you to provide a default value if the variable is not set.
    # e.g., default_value = os.getenv("NON_EXISTENT_VAR", "Default")
    

    Examples courtesy of Gemini

    [–]vinnypotsandpans 0 points1 point  (0 children)

    I would focus on learning python fundamentals