Issue
I have a file with variables
//data.txt
M = 100
m = 1
E = 5
j = 1
s = 1
I use the following function to load the data into a python script
def load_file(path):
if not os.path.isfile(path):
print('Parameters file not found.')
exit()
module_name = os.path.basename(path).replace('-', '_')
spec = importlib.util.spec_from_loader(
module_name,
importlib.machinery.SourceFileLoader(module_name, path)
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[module_name] = module
return module
In the main script, the usage would be
import sys
import os
import importlib
data = load_file('data.txt')
print(data.M)
I can access the variable names with data.Variable
. The question I have is how do I check if data contains all the variables it should?
Solution
If you want to check if the variables are defined maybe you can use dir
:
print(set(['E', 'M','j', 'm', 's']).issubset(dir(data))) # Prints True if all variable are defined
Answered By - Pedro Maia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.