0

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • Unless there's something I'm not understanding about this, why not make it a module and do `import data_file.py` instead? – shuttle87 Nov 14 '13 at 23:58

2 Answers2

3

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.

Community
  • 1
  • 1
shuttle87
  • 15,466
  • 11
  • 77
  • 106
2

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.

Jud
  • 1,158
  • 1
  • 8
  • 17
  • it's saying that my file isn't a module ? do you have any idea why ? – O.rka Nov 15 '13 at 00:05
  • Where is `data_file.py` in the filesystem relative to `new_python.py` (and also to `$PYTHONPATH`)? I'll edit my answer to show how you can add a path it. – Jud Nov 15 '13 at 00:06
  • in a completely different folder, but i specified the path with data_file . is that not enough ? – O.rka Nov 15 '13 at 00:07