Skip to main content

Imports

Ok so you have your code in separate files.  You may have even installed a few packages to extend the functionality of the base python library.  To get these packages, modules, functions or other items into your application for use we have to explore the ways in which we can import.

Given this folder structure

\MovieManager
    movieManager.py
    
    \folderScanner
        folderScanner.py
        
        \fileParsers
          xmlParser.py
          vidParser.py
          audParser.py
          picParser.py

Within the movieManager.py file you can import the other modules pretty easily.

# movieManager.py

from folderScanner import scanFolder

movieFolder = "/var/movies/someMovie (2019)"

scanFolder(movieFolder)

Within the folderScanner.py file you would then import the parts needed to scan that folder.  The underscore as a first character in your function definition indicates to other programmers that the function is not intended to be imported directly.

# folderScanner.py
import os  # Import from the python standard library

from xmlParser import parseXML
from audParser import parseAudio
from vidParser import parseVideo
from imgParser import parseImage

unknownFiles = []
xmlFiles = []
audFiles = []
vidFiles = []
imgFiles = []

def scanFolder(pathToMovieFolder):
  for item in os.listdir(pathToMovieFolder):  # listdir generates a list of all things within a directory
    if _isXML(item):
      xmlFiles.append(parseXML(item))  # Use the xml parser to extract data and store it in xmlfiles list
    
    elif _isAUD(item):
      audfiles.append(parseAudio(item))  # Use the audio parser to extract data and store it in audfiles list
      
    elif _isVID(item):
      vidFiles.append(parseVideo(item))  # Use the video parser to extract data and store it in vidfiles list
      
    elif _isIMG(item):
      imgFiles.append(parseImage(item))  # Use the image parser to extract data and store it in imgfiles list
      
    else:
      unknownFiles.append(item)  # Unsupported file found, store it for later.  Maybe we want to delete them.

def _isXML(filePath):
  """is this an xml file"""
  pass

def _isAUD(filePath):
  """is this an audio file"""
  pass

def _isVID(filePath):
  """is this a video file"""
  pass

def _isIMG(filePath):
  """is this an image file"""
  pass

Other ways to import include:

# movieManager.py
from folderScanner import folderScanner			# Import the entire module
from folderScanner import *						# Import the entire module giving you access to everything within it
from folderScanner.imgParser import someFunct	# Import directly from the image parser (traversing directory)
from folderScanner import audFiles				# Import the list of audio files
from folderScanner import _isIMG				# leading "_" doesn't prevent importing

Even more ways:

# movieManager.py
import .folderScanner.folderScanner  # Relative import (generally not used)
from .folderScanner import folderScanner # Another Relative import