data_file.py --> the following is the contents of data_file.py
numbers = [1,2,3,4,5]
alpha = ['a','b','c','d','e']
D_num_alpha = dict(zip(numbers,alpha))
new_python.py
data_file = '/Users/user/desktop/data_file.py'
open(data_file,'r').read()
print numbers
>>>NameError: name 'numbers' is not defined
I'm trying to use this dictionary made in data_file.py inside of new_python.py but i can only read it into a string.
2 Answers 2
Given that your data file is a python script then you might wish to import this instead by doing:
from data_file import numbers
print numbers
If the python file you are attempting to import is in a different directory it takes a bit more effort, for that you have to do the following:
Change your code to tell python where to look for the module:
import sys
sys.path.append( "path to include directory")
from data_file import numbers
print numbers
Create an empty file called __init__.py
in the same directory as the file you are importing. This tells python that you want to be able to use the folder with import. You can read more about why you need __init__.py
over at the documentation here.
Note that there are a few different was in which you might want to tell python how to import from a different directory, see this question for more info.
You might also want to see this PEP about relative imports.
No need for any nasty eval()
that way that could potentially introduce problems later on.
If you're confident that neither script will be tampered with you could use eval()
.
Your code would look like this:
data_file = '/Users/user/desktop/data_file.py'
eval(open(data_file,'r').read())
print numbers
EDIT: Another method is to import the data_file.py as a module. If data_file.py
is in /path/to/data
import sys
sys.path.append('/path/to/data')
import data_file
print data_file.numbers
This is a better approach, unless you have a specific reason why you don't want the entirety of data_file.py
evaluated.
-
it's saying that my file isn't a module ? do you have any idea why ?O.rka– O.rka2013年11月15日 00:05:42 +00:00Commented Nov 15, 2013 at 0:05
-
Where is
data_file.py
in the filesystem relative tonew_python.py
(and also to$PYTHONPATH
)? I'll edit my answer to show how you can add a path it.Jud– Jud2013年11月15日 00:06:43 +00:00Commented Nov 15, 2013 at 0:06 -
in a completely different folder, but i specified the path with data_file . is that not enough ?O.rka– O.rka2013年11月15日 00:07:47 +00:00Commented Nov 15, 2013 at 0:07
import data_file.py
instead?