[python] Import module from subfolder

I want to import subfolders as modules. Therefore every subfolder contains a __init__.py. My folder structure is like this:

src\
  main.py
  dirFoo\
    __init__.py
    foofactory.py
    dirFoo1\
      __init__.py
      foo1.py
    dirFoo2\
      __init__.py
      foo2.py

In my main script I import

from dirFoo.foofactory import FooFactory

In this factory file I include the sub modules:

from dirFoo1.foo1 import Foo1
from dirFoo2.foo2 import Foo2

If I call my foofactory I get the error, that python can't import the submodules foo1 and foo2:

Traceback (most recent call last):
  File "/Users/tmp/src/main.py", line 1, in <module>
from dirFoo.foofactory import FooFactory
  File "/Users/tmp/src/dirFoo/foofactory.py", line 1, in    <module>
from dirFoo1.foo1 import Foo1
    ImportError: No module named dirFoo1.foo1

This question is related to python import module subdirectory

The answer is


Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

Say your project is structured this way:

+---MyPythonProject
|   +---.gitignore
|   +---run.py
|   |   +---subscripts
|   |   |   +---script_one.py
|   |   |   +---script_two.py

Inside run.py, you can import scripts one and two by:

from subscripts import script_one as One
from subscripts import script_two as Two

Now, still inside run.py, you'll be able to call their methods with:

One.method_from_one(param)
Two.method_from_two(other_param)

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like "-" or "_". If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the 'targetClass.py' file inside the Generic-Class-Folder file to use the function named "functionExecute" in 'targetClass.py' file

What command I did?

  • from 'testFile.py', wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong......

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this... just letting my frustrations go.... :) Thanks!)


Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages


Had problems even when init.py existed in subfolder and all that was missing was adding 'as' after import

from folder.file import Class as Class
import folder.file as functions

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to import

Import functions from another js file. Javascript The difference between "require(x)" and "import x" pytest cannot import module while python can How to import an Excel file into SQL Server? When should I use curly braces for ES6 import? How to import a JSON file in ECMAScript 6? Python: Importing urllib.quote importing external ".txt" file in python beyond top level package error in relative import Reading tab-delimited file with Pandas - works on Windows, but not on Mac

Examples related to module

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7 How to import functions from different js file in a Vue+webpack+vue-loader project Typescript ReferenceError: exports is not defined ImportError: No module named tensorflow ModuleNotFoundError: What does it mean __main__ is not a package? ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import module.exports vs. export default in Node.js and ES6 What's the difference between an Angular component and module Export multiple classes in ES6 modules Python - Module Not Found

Examples related to subdirectory

Correctly ignore all files recursively under a specific folder except for a specific file type How do I get a list of folders and sub folders without the files? List all files and directories in a directory + subdirectories Import module from subfolder Browse files and subfolders in Python Vbscript list all PDF files in folder and subfolders Pick images of root folder from sub-folder PHP Get all subdirectories of a given directory How to create nonexistent subdirectories recursively using Bash? Import a file from a subdirectory?