0

I'm going through the Python tutorial, and I got to the section on modules.

I created a fibo.py file in Users/Me/code/Python (s

Now I'm back in the interpreter and I can't seem to import the module, because I don't understand how to import a relative (or absolute) path.

I'm also thoroughly confused by how and if to modify PYTHONPATH and/or sys.path.

All the other 'import module' questions on here seem to be

Craig
  • 16,291
  • 12
  • 43
  • 39
  • 3
    There's lots of truncated text in this question. You should be explicit about what all the paths involved are. – Will Dean Nov 09 '10 at 22:08
  • Agreed. Just a reminder it is considered best practice to either put your global modules in python itself (the site-packages folder) or to just put the module in the same directory as the python program you are currently running. – Joshkunz Nov 09 '10 at 22:50
  • "All the other 'import module' questions on here seem to be" incomplete? unfinished? broken? – S.Lott Nov 10 '10 at 02:24
  • Google seems to lead here. I recommend people check out [this answer](https://stackoverflow.com/a/14132912/5289570) as of today. – Wassadamo Nov 23 '22 at 23:12

4 Answers4

5
import sys

sys.path.append('your/dir')

import yourmod
Conner
  • 30,144
  • 8
  • 52
  • 73
2371
  • 957
  • 1
  • 6
  • 19
1

The only way to have paths for imports is when these are submodules or subpackages of some packge. This is explained in the tutorial.

PYTHONPATH defines in which directories, other than the current working directory, the interpreter looks for an import. So, suppose you have your module at /Users/Code/Me/Python/fibo.py. If you set PYTHONPATH to /Users/Code/Me/Python/, you will be able to import your module like this:

import fibo
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
0

Before importing any user defined module,specify the path to the directory containg that module sys.path.append("path to your directory")

vinayv
  • 1
  • 3
0

If you're just testing, you can do

import os
os.chdir(<directory-with-your-module>)
import fibo
Katriel
  • 120,462
  • 19
  • 136
  • 170