-1

I know the general process of importing the python file. The importing file and the file in which we want to import must be present in same directory.

If I want to import the file which is present in some other directory by using absolute path, I can able to do it.

But with out using absolute path how to import the python file in any other directory. is there any process by using relative path for importing the file.

  • Add the folder that contains the module you want to import to the `PYTHONPATH` environment variable, or do `sys.path.append("path_to_folder")`. – BoarGules Jan 01 '19 at 13:25
  • Theoretically you can do your task by iterating all directories to find out where file you need is kept. Then you can get an absolute path to import the file. But it's very time consuming approach. Why do you have to use relative path? – Sergey Solod Jan 01 '19 at 14:02

1 Answers1

1

you can obtain current directory using os module and then add the relative path from the current directory of the file e.g.

import os
import sys
cur_dir = os.path.dirname(__file__)
target_dir = os.path.join(cur_dir, "relative path of target dir")
sys.path.insert(0, target_dir)
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19