2

I wanted to load a module named mymodule in a directory up two, and down one directory in my file system. Elsewhere I have used

import sys
sys.path.append('../mydirectory')
import mymodule # in mydirectory

in order to go up one, then down one directory (in a package) to grab a module, so I expected this to work:

import sys
sys.path.append('../../mydirectory')
import mymodule

However, I get a ModuleNotFoundError: "No module named 'mymodule'". I'm confused because I ran this in a directory down one from the directory where I had the previous (working) program. (I tried adding __init__.py but it didn't help.) Does anyone know why this doesn't work? Any advice?

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111

1 Answers1

4

this is my go-to-method for just that:

import sys
from pathlib import Path

HERE = Path(__file__).parent

sys.path.append(str(HERE / '../../mydirectory'))

using __file__ i do not rely on the current working directory as starting point for relative paths - HERE is the directory the current file is in.

of course you do not have to use the pathlib module.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • It works great, thanks! :) Still kind of curious whether I'm wrong to feel as though what I tried should "morally speaking" work. – Lucius Schoenbaum Jun 17 '17 at 14:51
  • relative paths will be taken with respect to your current working directory `os.getcwd()`. if that path matches the path your file is in, everything works! but if you start your program with something like `$ python some_dir/program.py` then it will not... – hiro protagonist Jun 17 '17 at 15:14
  • When I read your reply I thought it must have been the text editor I was running from (it may have been using a working directory other than the location of the file that is open in the active window as I would have assumed), but now when I run it IT DOES WORK and a print(os.getcwd()) shows the `__file__` directory...so the only question I have left now is why in the world it wasn't working before? Ah well. Your point is well taken, I will use Path. Thank you! :) – Lucius Schoenbaum Jun 18 '17 at 03:56