How to update a int value on a .env file using python

Question:

I have a problem doing this python file . The idea its that this python file could change a int value in a .env file . The problem its that i could change the value of the field in the env , but the value is formated , I insert in the program a number , and in the .env it shows like ‘number’ , so i want to change it to only the number

    import os
import dotenv
import sys
from os import environ
from dotenv import load_dotenv




day=input("Insert day: ")

car1=input("Insert car1 : ")

car2=input("Insert car2 : ")

load_dotenv("config.env")
#       print(os.environ["DAY"])  # outputs "valor original"
os.environ["DAY"] = day
#       print(os.environ['DAY'])  # outputs 'valor nuevo'

#       print(os.environ["CAR1"])  # outputs "valor original"
os.environ["CAR1"] = car1
#       print(os.environ['CAR1'])  # outputs 'valor nuevo'

#       print(os.environ["CAR2"])  # outputs "valor original"
os.environ["CAR2"] = car2
#       print(os.environ['CAR2'])  # outputs 'valor nuevo'


dotenv.set_key("config.env", "DAY", os.environ["DAY"])
dotenv.set_key("config.env", "CAR1" , os.environ["CAR1"])
dotenv.set_key("config.env", "CAR2" , os.environ["CAR2"])

And in the config.env file it shows like this

## Config

SCNAME="EXAMPLE"
DAY='77'

# CAR 1
CAR1='88'


# CAR 2
CAR2='99'

When i want that the values i want to change were shown as a int , without (‘),like :

DAY=77
CAR1=88
CAR2=99 

Thanks all for attention and helping me guys

Asked By: triplero34

||

Answers:

TL, DR

dotenv.set_key("config.env", "DAY", os.environ["DAY"], quote_mode='never')

Details

When you type, the input is a string.
day = input(...) will save a string in day.

You should use int() to convert it to an integer before saving it in day.

day = int(input("Insert day: "))

However, this can not be secure given that the user can write anything on the keyboard. You can first save the input and check if it is OK. before putting in day and writing it in your env file.

day_input = input("Insert day: ")

# You can add any other verification to the user input
if not day_input.isdigit():
  # Tell user he made a mistake
else:
  day = int(day_input)

You can also use Try-Except to handle these errors:

while True:
    value = input('write an integer between 1 and 31')
    try:
       value = int(value)
    except ValueError:
       print('Valid integer, please')
       continue
    if value > 0 and value <= 31 : # Ok
       break
    else:
       print('Valid range, please: 1-31')

see How do I use try .. except or if …else to validate user input?

Moreover, you cannot put integer values in .env files. These accept only strings as values.

def set_key(
    dotenv_path: Union[str, _PathLike],
    key_to_set: str,
    value_to_set: str,
    quote_mode: str = "always",
    export: bool = False,
    encoding: Optional[str] = "utf-8",
) -> Tuple[Optional[bool], str, str]:

This is extracted from the set_key() method from dotenv and you can see that it accepts only str type for value argument. os.environ checks that also. So you cannot put directly integers there.

However, in dotenv.set_key(), you can see that there is a quote_mode. You can write :

dotenv.set_key("config.env", "DAY", os.environ["DAY"], quote_mode='never')

You can either use another format instead of .env or you can make sure to convert values before and after writing/reading the env file.

Answered By: inarighas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.