0

I am making a script (python) and need to import other files (complete). The file I would like to import, is 2 directories up from the script.

Normal in Python you would do something like

../../../file.py <-- goes up 3 directories

When I do this in Python it gives a syntax error.

..file for example works but as soon as I chain it ../..file.py the syntax error comes in.

I tried
../..file
../../file
/../..file
/../../file

The error says invalid syntax.

The complete command is

from ../..file import *

I would like to import all the content of the file.

The path needs to be relative due to the nature of the script. No hardcoding allowed. How can I go up multiple directories in Python?

Neuron
  • 5,141
  • 5
  • 38
  • 59

1 Answers1

0

importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

If you want to import the whole file you can just do import file. Then you can choose the function that you are interesting in. for example:

import FULL_PATH_TO_MY_FILE
my_file.my_func...

or you can try:

from FULL_PATH_TO_MY_FILE import *

and then you can use each function in your file like this - myfunc()

Tal Folkman
  • 2,368
  • 1
  • 7
  • 21