0

I'm having a little issue with my package directories. The structure is as follows:

  • package folder with modules
    • Databases

In the package folder I have a lot of .py files with functions that I use from everywhere (so on another drive as well). Some functions like "guess_countries" use databases located in a subfolder. I did that because I want to export my code to github (private repo).

Here is the issue:

My module Geo_guesser needs to look for this path (so a subfolder): "Databases/Geo/Countries/Countries (ZIP+Dump).sqlite3"

However upon importing from another folder the current directory gets appended and it becomes "Z:/Other_folder/Databases/Geo/Countries/Countries (ZIP+Dump).sqlite3" instead of "A:/My_package/Databases/Geo/Countries/Countries (ZIP+Dump).sqlite3" where the databases are.

I don't want to use absolute paths because everything is contained in the package folder and in the future I'd like to make it pip-installable or maybe share it with others and so the absolute path won't be the same obviously.

Other infos:

In the module Geo_guesser I've tried using: os.path.realpath, __file__ and sys.argv without success (I looked up many topics before posting this).

I used conda develop to be able to import my package's modules from anywhere

Tools:

Anaconda, Python 3.6 and Jupyter

Thanks in advance for the help :)!

ThibTrip
  • 21
  • 3
  • 2
    Hi and Welcome. What does your actual code look like? Where you do the "import" and the code relevant to the `Z:` vs `A:` mixup. – Torxed Oct 24 '18 at 12:10
  • Welcome to Stack Overflow! To give you a great answer, it might help us if you have a glance at [ask] if you haven't already. It might be also useful if you could provide a [mcve]. – Mat Oct 24 '18 at 12:14
  • I do the import in "Z:/Other_folder/some_notebook.ipynb" from a module located in "A:My_package/" but as you can see in my answer it seems I found a solution :) – ThibTrip Oct 24 '18 at 12:31

1 Answers1

0

Well nevermind I finally found a code that works for me sorry :( :

import os, sys, inspect

# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
    sys.path.insert(0, cmd_folder)

Source: Import a module from a relative path

ThibTrip
  • 21
  • 3