0

A get an error when trying to run my code but somehow vs code doesn't see the path error.

The error:

ModuleNotFoundError: No module named 'get_formats'

The structure of my code is:

application
├── data_processor
│   ├── extract_movements.py
│   └── get_formats
│       └── get_formats.py
├── get_user_input
│   ├── get_bank_name.py
│   └── get_pdf_name.py
└── operate.py

And the error occures in extract_movements.py where I am trying to import a funtion located in get_formats.py using:

from get_formats.get_formats import get_transaction_tags_format, get_transaction_dates_format

The complete error shown is:

Traceback (most recent call last):
  File "/Users/username/Desktop/application/operate.py", line 6, in <module>
    from data_processor.extract_movements import extract_movements
  File "/Users/username/Desktop/application/data_processor/extract_movements.py", line 1, in <module>
    from get_formats.get_formats import get_transaction_tags_format, get_transaction_dates_format
ModuleNotFoundError: No module named 'get_formats'

I see some answers talk about an __init__.py file in the application directory or the data_processor directory so i tried adding that but got no results. Also have no idea what an empty file with the name __init__.py

Chris
  • 704
  • 1
  • 11
  • 32
  • maybe put a try except block, trying to import it how you are, and except with ```from data_processor.get_formats.get_formats import get_transaction_tags_format, get_transaction_dates_format``` As the originating file is in the main directory, it cannot find the "get_formats" file in the main directory. – Mitch97 Apr 12 '21 at 00:26
  • Does that mean that any time I import a function into a new file I call it from the main directory? I feel stupid cause that works and I can't believe I didn't try that Well didn't use try and except just replaced the code – Chris Apr 12 '21 at 00:31
  • Does the __init__.py code have anything to do with this? – Chris Apr 12 '21 at 00:33

1 Answers1

0

If you make an __init__.py script in your directory, you'll be able to access sibling files.

Why wasn't your __init__.py working? - You need an __init__.py inside the get_formats directory not outside, otherwise that directory will not be treated as a module.

However the easiest option is to use the sys module, like sys.path.append in the second answer here Importing files from different folder , or like this: How to import .py file from another directory?