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

4
  • 3
    There's lots of truncated text in this question. You should be explicit about what all the paths involved are. Commented Nov 9, 2010 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. Commented Nov 9, 2010 at 22:50
  • "All the other 'import module' questions on here seem to be" incomplete? unfinished? broken? Commented Nov 10, 2010 at 2:24
  • Google seems to lead here. I recommend people check out this answer as of today. Commented Nov 23, 2022 at 23:12

4 Answers 4

5
import sys

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

import yourmod
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

It also looks in the current directory
@Falmarri: That is why I wrote other than the current working directory.
Sorry, totally missed that =\
0

If you're just testing, you can do

import os
os.chdir(<directory-with-your-module>)
import fibo

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.