The from x import y
import mechanism in Python is specifically designed to work with Python modules (.py files). It looks for a module named x
and then imports the name y
defined inside it.
A .pem
file is simply a text file containing data and not a Python module, you cannot
directly use this import syntax to access its contents.
Instead, you should read the .pem
file's content within a Python module located (for example) in your lib
directory and then import that content.
Make a new Python file in your lib
directory called sharepoint_credentials.py
.
import os
def load_sharepoint_key(filename="sharepoint_key.pem"):
filepath = os.path.join(os.path.dirname(__file__), filename) # sharepoint_key.pem file in the lib directory
try:
with open(filepath, 'r') as f:
private_key = f.read().strip()
return private_key
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return None
SHAREPOINT_PRIVATE_KEY = load_sharepoint_key()
You can now access the content by importing it into your various Python scripts.
import sys, os
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_dir, "..", "..", ".."))
import __root__
from lib.sharepoint_credentials import SHAREPOINT_PRIVATE_KEY, load_sharepoint_key
if SHAREPOINT_PRIVATE_KEY:
print("Loaded SharePoint Private Key:")
print(SHAREPOINT_PRIVATE_KEY)
else:
print("Failed to load SharePoint Private Key.")
# Or you can call the function directly if needed
key = load_sharepoint_key()
if key:
# Use key