Jump to content
  • Advertisement
Sign in to follow this  

Accessing other directories

This topic is 1364 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post

Link to post
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:


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

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!