I'm trying to write a code with exec and eval function to read lists of variables from a numpy .npz file.
When I ran the code without defining it as a function def, the code worked. However, when I ran the code as a function, i.e. read_file_npz("file_address") , the python 3.7 kept pop up message saying that templet_1h was not defined.
def read_file_npz(file_names_2):
import numpy as np
Delete_elements=["arr_0"]
evaluate_1= "templet_1h=np.load(\"./" +file_names_2+ ".npz\")";
exec(evaluate_1)
for i in (templet_1h.files):
if not ( (i in Delete_elements) ):
evaluate_2="global "+i;
exec(evaluate_2)
evaluate_2= i+"="+"templet_1h[\"" + i + "\"]";
exec(evaluate_2)
What's wrong with the warning and how to modify it?
I tried to declear templet_1h before the code as list(), but then the warning became .files had no ... towards lists, as if evaluate_1 was never ran.
Use exec(evaluate_1, globals())
instead to use the global dictionary for global and local variables in exec
.
The code adds the defined variable to the global dictionary. Adding it as local variable of a function is not possible.