So I have a program with one main module that is in a folder with two other folders. Each of those two folders has a module in it that I've imported successfully, but each of those modules is supposed to be able to open and read a file from their respective folders, but it is unable to find the file it is supposed to import. I think it is looking in the main directory for the file to open, how would I make each module look in its own folder for the files to open?
3 Answers
My suggestion is to consider using the os.path
module to ensure that you are using the correct paths when you open files. Here are a few operations that you might find helpful:
os.path.abspath(path)
transformspath
into an absolute path.os.path.dirname(path)
gives the name of the directory ofpath
.os.path.join(path1, path2)
combinespath1
andpath2
.
Documentation for Python 2: https://docs.python.org/2/library/os.path.html#module-os.path Documentation for Python 3: https://docs.python.org/3/library/os.path.html#module-os.path

- 46
- 4
If i understand the question correctly, you want the ability to import a file from any directory in the system? If that is the case you can use libraries (depending on your version of python) such as importlib.util, or imp for python 2.
You can find documentation here: https://docs.python.org/3/library/importlib.html

- 365
- 3
- 16
-
the goal isn't to import from any directory, the goal is to have the imported modules import from there own directories instead of the directory they're imported into. Not sure if this is entirely possible the way I want to do it, its been about a week since I've started learning python so I'm not that familiar yet. – Jonah Neugeboren Jun 22 '16 at 14:28
-
Well it might be a good idea to take a look at this similar post and see if its what you're looking for: http://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path – gavsta707 Jun 22 '16 at 14:30
It sounds like there's probably a better way of doing what you're trying to do, but absent additional information, a module's location can be found (for use in file operations) in its __file__
variable:
mydir = os.path.dirname(__file__)

- 7,550
- 4
- 27
- 37