5

I'm using Python 3. I have two Python files in the same directory: first.py and second.py. In the beginning of first.py, I use:

from second import *

However, it returns the following error message:

ModuleNotFoundError: No module named 'second'

How should I import it in first.py?

Update: To clarify my specific use-case, I am trying to split my settings.py in Django. I have a main settings.py file and another one that only includes the confidential information. I followed this following documentation that uses the following line in settings.py:

from settings_local import *

Note that settings_local.py is in the same directory. However, it returns the following error message:

ModuleNotFoundError: No module named 'settings_local'

I know the document says "Some of the examples listed below need to be modified for compatibility with Django 1.4 and later." but I do not know how to use it in Python 3.

1man
  • 5,216
  • 7
  • 42
  • 56
  • 1
    Where are you running the script from? You should be able to import from Python files contained in the folder where you run the script. If you run the script from the same folder as the script, you shouldn't get this error. – Jeremy McGibbon Sep 20 '17 at 03:27
  • Basically, I am trying to split my settings.py in Django. I have a main settings.py file and another one that only includes the confidential information. I followed the following documentation, but it does not work: https://code.djangoproject.com/wiki/SplitSettings#Multiplesettingfilesimportingfromeachother – 1man Sep 20 '17 at 03:29

5 Answers5

8

I just found the solution:

from .settings_local import *

instead of:

from settings_local import *

I found the solution in this thread.

1man
  • 5,216
  • 7
  • 42
  • 56
3

You can use the following code snippet:

from .settings_local import *

This is relative import. More Info here and here

dalonlobo
  • 484
  • 4
  • 18
0

You can add files into Python this way

import sys
sys.path.insert(0, '/path/to/application/app/folder')
import file
Oscar Chambers
  • 899
  • 9
  • 25
0
you can create __init__.py in current directory.

then you can use:

from second import *

The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the __all__variable, described later.

wwl1991
  • 126
  • 4
0

You should be able to automatically add the directory the file is in to the PATH, and then import the other file, with this:

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import second
Jeremy McGibbon
  • 3,527
  • 14
  • 22