3

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
1
  • 1
    You need to print(dados.x) Commented Oct 12, 2017 at 23:51

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

from dados import x*
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.