Reputation: 30687
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.
Upvotes: 0
Views: 4822
Reputation: 15934
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.
Upvotes: 3
Reputation: 1188
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.
Upvotes: 2