Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically importing files in Python

Tags:

python

I wish to be able to import a file in Python whose source is a text file that will be often modified.

In other words, let's suppose that I have a file name, dados.py whose content in a given moment is:

x=[2, 3, 7, 9]

(and this is the only line of the file (possible?))

and my main program has the line

import dados

What I want is that when the import is made I will have an array with the values seen above.

But, if the values of the file dados.py change, the next time that the main program runs it will work with the new values.

The thing is that I don't know if I can have a line of code with variables and if python will recognize that it must execute this line.

The question I am trying to explain in details is because I had a working program with the x=[2, 3, 7, 9] writen on the source code. The moment that I replaced that line by:

import dados

line, python complains with a message like

File "testinclude.py", line 15, in <module>
    print(x)
NameError: name 'x' is not defined
like image 219
user2969291 Avatar asked Nov 19 '25 12:11

user2969291


1 Answers

Your variable is defined within a module, so you must namespace the variable

import dados
print(dados.x)

Or you can import x from dados

Alternative solution would be to use some JSON or other configuration file, then read and load it. It's not clear why you need a Python file only to define variables

like image 119
OneCricketeer Avatar answered Nov 21 '25 01:11

OneCricketeer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!