1

I am trying to import a module (not a file) from a different path.

By module, I mean that I have a folder named Util containing a single file named __init__.py.

Using import Util in a python file on the same level as the Util folder works fine.

But this is not the case when the python file resides elsewhere.

Following this answer, I have this piece of code working:

import sys,os
sys.path.append(os.path.dirname(__file__)+'the relative path to the python file that I want to import')

But it works only when I import a python file, not a python module.

How can I resolve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
goodvibration
  • 5,980
  • 4
  • 28
  • 61
  • Note that we prefer a technical style of writing here. We gently discourage greetings, hope-you-can-helps, thanks, advance thanks, notes of appreciation, regards, kind regards, signatures, please-can-you-helps, chatty material and abbreviated txtspk, pleading, how long you've been stuck, voting advice, meta commentary, etc. Just explain your problem, and show what you've tried, what you expected, and what actually happened. – halfer Jun 21 '20 at 12:01

1 Answers1

0

Problem solved:

Due to the fact that I am using Windows, the string os.path.dirname(__file__)+'the relative path to the python file that I want to import' contains a mixture of forward slashes (/) and backward slashes (\).

The simple solution is to ensure that the (OS-dependent) expression os.path.dirname(__file__) contains only forward slashes:

os.path.dirname(__file__).replace('\\','/')

Same goes for the constant part 'the relative path to the python file that I want to import' of course, which one can simply fix manually if needed (I already had this one with forward slashes only).

goodvibration
  • 5,980
  • 4
  • 28
  • 61