user2969291
user2969291

Reputation: 61

Dynamically importing files in 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

Upvotes: 3

Views: 74

Answers (2)

Austin A
Austin A

Reputation: 566

In this instance it is probably better to use a file instead of a python module. However, if you insist on using a module, you can store the data in a variable and access it using the "." operator.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191884

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

Upvotes: 2

Related Questions