0

I have two files first_file and second_file in the same directory dir. When I am trying to import second_file in first_file using

from dir import second_file

I am getting ImportErorr. I have also tried using

from . import second_file

in the first_file but still I am getting that error. I am using Python 3.6 How to import correctly?

Sri Divya
  • 59
  • 5

1 Answers1

1

You are importing wrongly. To get a file that is in the same dictionary use:

import second_file

Assuming the following structure:

dir -|
      -  __init__.py
      -  first_file.py
      -  second_file.py

You will also need an __init__.py file (see why here)

The command:

from dir import second_file

Will import second_file from a package (or sub-folder) with the following structure:

main_folder |-
              |-  first_file.py
              |-  dir  |-
                         |-  __init__.py
                         |-  second_file.py

from . import second_file will have this structure:

main_folder |-
              |- __init__.py
              |- second_file.py
              |- dir |-
                       |- first_file.py

The section of the Python documentation relating to modules might be helpful to you as well.

Xantium
  • 11,201
  • 10
  • 62
  • 89
  • @SriDivya Hmmm What is your file structure? Also what does your `__init__.py` contain? This is certainly the way to import without more details it is not apparent why it is not. – Xantium Feb 16 '18 at 15:16