0
-Booking
    -components
        -db.py
    -scripts
        -insert_data.py

How do I import db.py in insert_data.py? (I'm using python 3)

  • Where is your current working directory? Where are you trying to import the script to? – C.Nivs Dec 09 '19 at 21:55
  • 1
    `components` needs an [`__init__.py`](https://stackoverflow.com/questions/448271/what-is-init-py-for). – 0x5453 Dec 09 '19 at 22:00

3 Answers3

0

from components import db

Should work as long as components has a (potentially empty) __init__.py in it

samfr
  • 656
  • 1
  • 6
  • 19
0
  1. Put __init__.py inside components folder
  2. Access it from scripts folder using from ..components import db
0

There are several options, and it helps to know how Python's modules and packages work (which is not always completely straightforward and intuitive):

One way is to explicitly modify the module search path in the beginning of your script:

import sys, os
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'components'))
import db

A less hacky way uses relative import, as described in Importing from a relative path in Python and Execution of Python code with -m option or not.

sammy
  • 857
  • 5
  • 13