1

I know that I can import a python module by using their file path, but is there a way to import a file relative to the current file's position?

For example, it seems like I can "import file" only if the script is in the same folder as the one I am working with. How can I import the file if it's in the folder outside of mine, or one below the hierarchy, without giving the full file path? I would like it so that I can move the project folder around and still have everything work.

wrxryuu
  • 33
  • 1
  • 6
  • Possible duplicate of [Import modules from different folders](https://stackoverflow.com/questions/13598958/import-modules-from-different-folders) – Chiheb Nexus Jun 01 '17 at 23:03

1 Answers1

0

I'm afraid that is impossible to import single python files using their paths. In python you have to deal with modules. The finest solution would be to create a module from your outside-folder script and put in your system modules path.

Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41
  • What about `sys.path.append('/home/dir1/dir2/dir3')` – Chiheb Nexus Jun 01 '17 at 23:04
  • Only if it is the path to a folder that contains modules (and not just python script files). The documentation says: *The variable sys.path is a list of strings that determines the interpreter’s search path for modules* – Ilario Pierbattista Jun 01 '17 at 23:09
  • 1
    So, along the documentation you can modify this `sys.path` (which is a list of strings) and add the folder's path where the desired python file is. This is not recommended but still a valid hack to do it. Also, using an empty file called `__init__.py` can do the trick too. Also, this question is duplicate from this [question](https://stackoverflow.com/questions/13598958/import-modules-from-different-folders). – Chiheb Nexus Jun 01 '17 at 23:13
  • I was wondering if there was a way to avoid using file path at all if I know the files' relative position so it's a bit different than the other question. Thanks for the help btw! – wrxryuu Jun 01 '17 at 23:17
  • @wrxryuu an empty file called `__init__.py` ? Take a look at the other question. You'll find what you need. – Chiheb Nexus Jun 01 '17 at 23:19
  • oh ugh sorry, YES. That's what I was looking for. I didn't scroll down far enough because the first answer was not what I was looking for. Thank you so much! – wrxryuu Jun 02 '17 at 18:33