0

I am working on some code that requires importing a module from a directory several levels up and down. Here is the code:

import os
import pathlib 


#
## Print path to this file
my_name = pathlib.Path(__file__)
my_path = pathlib.Path.cwd()
home_path = pathlib.Path.home()
lib_path = my_path.parents[3]

# log_path = lib_path / 'providers' / 'logging' / 'logger_uk'

log_path = lib_path.joinpath('providers', 'logging', 'logger_uk')
log_path_str = str(log_path)


'''
  print(f"{my_name} located in: {my_path}")
  print(f"Home directory is: {home_path}")
  print(f"Library directory is: {lib_path}")
'''

# from lib_path.logging.logger_uk import logger

#
## Import logger module
from log_path_str import logger


print(f"Log module path is: {log_path_str}")
print(os.listdir(log_path))

When I print log_path_str - it shows the correct path, but import is throwing the following error:

Traceback (most recent call last):
  File "path_finder.py", line 46, in <module>
    from log_path_str import logger
ModuleNotFoundError: No module named 'log_path_str'

What am I doing wrong?

martineau
  • 119,623
  • 25
  • 170
  • 301
Ubaidul Khan
  • 131
  • 3
  • 13
  • Python's `import` statement requires module names, not `Path`s (or strings containing equivalents to them) to modules. `import` statement are not like C/C++ `#include` directives. – martineau Jul 29 '21 at 18:10
  • This was the fix: `sys.path.append(log_path_str) from logger_uk import logger` – Ubaidul Khan Jul 29 '21 at 18:43
  • Appending a string containing the path to a folder containing a module to `sys.path` is a way to workaround the fact that you don't/can't use paths to modules in `import` statements. – martineau Jul 29 '21 at 18:48

0 Answers0