import json import base64 import os import dotenv # load the service account key with open(os.getcwd() +'/gcp_default_creds.json') as f: service_key = json.load(f) dotenv_file = dotenv.find_dotenv() dotenv.load_dotenv(dotenv_file) # convert json to a string service_key = json.dumps(service_key) # encode service key encoded_service_key = base64.b64encode(service_key.encode('utf-8')) encoded_service_key = str(encoded_service_key)[2:-1] print(encoded_service_key) # b'many_characters_here' os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = encoded_service_key print(os.environ['GOOGLE_APPLICATION_CREDENTIALS']) # outputs 'newvalue' # Write changes to .env file. dotenv.set_key(dotenv_file, "GOOGLE_APPLICATION_CREDENTIALS", os.environ["GOOGLE_APPLICATION_CREDENTIALS"])