1

I consider myself an intermediate user in python, and this one is a new one. Testing code in IDLE (Python 3.2.3) on Linux. Here is the entire script:

Python 3.2.3 (default, Apr 10 2013, 05:29:11) 
[GCC 4.6.3] on linux2
Type "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>> from os import listdir, getcwd, chdir
>>> chdir('Documents/matrix')
>>> getcwd()
'/home/bradfordgp/Documents/matrix'
>>> listdir('.')
['__init__.py', 'vec.zip', 'hw1.pdf', 'politics_lab.pdf', 'submit_hw1.py', 'submit_politics_lab.py', 'test_vec.py', 'Week1', 'Week0', 'python_lab.py~', 'Week2', 'vec.pdf', '__pycache__', 'hw1.zip', 'politics_lab.zip', 'voting_record_dump109.txt', 'my_stories.txt~', 'hw1.py', 'politics_lab.py', 'submit_vec.py', 'vec.py']
>>> from vec import Vec
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    from vec import Vec
ImportError: No module named vec
>>> 

I've navigated to the correct directory, and I'm importing from the same directory, and vec.py exists. Why is in not locating a file in the local directory? Running this script from a terminal window command line works correctly.

Suggestions?

Pat B.
  • 419
  • 3
  • 12
  • Check [**this**](http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path) for more details and answers – Adil Nov 13 '14 at 16:26

3 Answers3

2

use this..

import sys

sys.path.append("/home/bradfordgp/Documents/matrix")
import vec
abhishekgarg
  • 1,480
  • 9
  • 14
2
import sys
sys.path.append("/home/bradfordgp/Documents/matrix")
import vec

Rather than change to the directory, just add the location to the places python will search on import

See more here

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
0

In interactive mode, import will try to import modules from the current directory after os.chdir. But in non-interactive mode, it will fail and still search from the previous directory. You can see more discussion from this issue. In non-interactive mode, you'd better do what others mention.

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43