# Accessing other directories

## Recommended Posts

I've come across os.path.insert() which seems really good and appears to be cross platform.  The problem is though that there will be a lot of directories that I would have to add (especially since there will folders inside of folders). Plus if I do it this way I will making a text file for the main script to read from that will contain all the paths to be added.

I was wondering, is there is a better way of importing all the modules that I would need (and not just modules, but directories that contain json files and image files)?

##### Share on other sites

I'm assuming you mean sys.path, not os.path. If you want to be able to find and import Python code, there are better ways to do it.

First thing, though. If the problem is that you have multiple subfolders of code, and you cannot seem to import it, you're missing a crucial component in your "package" structure. Do you have an __init__.py file in all of your source code directories? If not, you should have them--they can just be empty files. (See https://docs.python.org/2/tutorial/modules.html#packages.) With these, your plain folders become Python "packages". (A "module" is just a file containing Python code which has a .py extension. A "package" is a folder which contains an __init__.py "module".)

An example:

foo/
__init__.py
some_module.py
some_other_module.py
bar/
__init__.py
baz.py
blarg/
__init__.py
utils.py


If you want to add the foo package to your path, so that you can import code from it, you can do this:

import sys
# you only need to add the root folder to your path
# if your folders have an __init__.py in them,
# python will traverse the folder structure and find all of the code
sys.path.insert(0, '/path/to/foo/')

# now you can make all sorts of imports statements:
import foo
import foo.some_module

from foo import some_other_module

import foo.bar
from foo.bar import baz

import foo.bar.blarg
from foo.bar.blarg import utils
# etc.


Instead of just putting code somewhere and patching the sys.path at runtime, there is a better way. It is better to install your code in a well-known way to a well-known location. See https://docs.python.org/2/distutils/setupscript.html. Another thing you can do add the path to the code to your PYTHONPATH environment variable. For distributing code, creating a proper setup.py file is better.

Edited by thok

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628330
• Total Posts
2982112

• 22
• 9
• 9
• 13
• 11