How to import other Python files? – Dev

The best answers to the question “How to import other Python files?” in the category Dev.


How do I import other files in Python?

  1. How exactly can I import a specific python file like import
  2. How can I import a folder instead of a specific file?
  3. I want to load a Python file dynamically at runtime, based on user
  4. I want to know how to load just one specific part from the file.

For example, in I have:

from extra import * 

Although this gives me all the definitions in, when maybe all I want is a single definition:

def gap():

What do I add to the import statement to just get gap from


importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

In python 2.x:

  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)

Type help(__import__) for more details.


There are many ways to import a python file, all with their pros and cons.

Don’t just hastily pick the first import strategy that works for you or else you’ll have to rewrite the codebase later on when you find it doesn’t meet your needs.

I’ll start out explaining the easiest example #1, then I’ll move toward the most professional and robust example #7

Example 1, Import a python module with python interpreter:

  1. Put this in /home/el/foo/

    def what_does_the_fox_say():
      print("vixens cry")
  2. Get into the python interpreter:

    [email protected]:/home/el/foo$ python
    Python 2.7.3 (default, Sep 26 2013, 20:03:06) 
    >>> import fox
    >>> fox.what_does_the_fox_say()
    vixens cry

    You imported fox through the python interpreter, invoked the python function what_does_the_fox_say() from within

Example 2, Use execfile or (exec in Python 3) in a script to execute the other python file in place:

  1. Put this in /home/el/foo2/

    def moobar():
  2. Put this in /home/el/foo2/

  3. run the file:

    [email protected]:/home/el/foo$ python

    The function moobar was imported from and made available in

Example 3, Use from … import … functionality:

  1. Put this in /home/el/foo3/

    def question():
      print "where are the nuclear wessels?"
  2. Put this in /home/el/foo3/

    from chekov import question
  3. Run it like this:

    [email protected]:/home/el/foo3$ python 
    where are the nuclear wessels?

    If you defined other functions in, they would not be available unless you import *

Example 4, Import if it’s in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/

    def watchout():
      print "computers are transforming into a noose and a yoke for humans"
  2. Put this in /home/el/foo4/

    import sys 
    import os
    from riaa import *
  3. Run it:

    [email protected]:/home/el/foo4$ python 
    computers are transforming into a noose and a yoke for humans

    That imports everything in the foreign file from a different directory.

Example 5, use os.system("python")

import os

Example 6, import your file via piggybacking the python startuphook:

Update: This example used to work for both python2 and 3, but now only works for python2. python3 got rid of this user startuphook feature set because it was abused by low-skill python library writers, using it to impolitely inject their code into the global namespace, before all user-defined programs. If you want this to work for python3, you’ll have to get more creative. If I tell you how to do it, python developers will disable that feature set as well, so you’re on your own.


Put this code into your home directory in ~/

class secretclass:
    def secretmessage(cls, myarg):
        return myarg + " is if.. up in the sky, the sky"
    secretmessage = classmethod( secretmessage )

    def skycake(cls):
        return "cookie and sky pie people can't go up and "
    skycake = classmethod( skycake )

Put this code into your (can be anywhere):

import user
msg = "The only way skycake tates good" 
msg = user.secretclass.secretmessage(msg)
msg += user.secretclass.skycake()
print(msg + " have the sky pie! SKYCAKE!")

Run it, you should get this:

$ python
The only way skycake tates good is if.. up in the sky, 
the skycookie and sky pie people can't go up and  have the sky pie! 

If you get an error here: ModuleNotFoundError: No module named 'user' then it means you’re using python3, startuphooks are disabled there by default.

Credit for this jist goes to: Send along your up-boats.

Example 7, Most Robust: Import files in python with the bare import command:

  1. Make a new directory /home/el/foo5/
  2. Make a new directory /home/el/foo5/herp
  3. Make an empty file named under herp:

    [email protected]:/home/el/foo5/herp$ touch
    [email protected]:/home/el/foo5/herp$ ls
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another file:

    [email protected]:/home/el/foo5/herp/derp$ touch
    [email protected]:/home/el/foo5/herp/derp$ ls
  6. Under /home/el/foo5/herp/derp make a new file called Put this in there:

    def skycake():
      print "SkyCake evolves to stay just beyond the cognitive reach of " +
      "the bulk of men. SKYCAKE!!"
  7. The moment of truth, Make the new file /home/el/foo5/, put this in there;

    from herp.derp.yolo import skycake
  8. Run it:

    [email protected]:/home/el/foo5$ python
    SkyCake evolves to stay just beyond the cognitive reach of the bulk 
    of men. SKYCAKE!!

    The empty file communicates to the python interpreter that the developer intends this directory to be an importable package.

If you want to see my post on how to include ALL .py files under a directory see here:


First case

You want to import file in file, these two files are in the same folder, like this:


You can do this in file

import A


from A import *



Then you will be able to use all the functions of file in file

Second case

You want to import file folder/ in file, these two files are not in the same folder, like this:

└── folder

You can do this in file

import folder.A


from folder.A import *


from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file in file


  • In the first case, file is a module that you imports in file, you used the syntax import module_name.
  • In the second case, folder is the package that contains the module, you used the syntax import package_name.module_name.

For more info on packages and modules, consult this link.


To import a specific Python file at ‘runtime’ with a known name:

import os
import sys

scriptpath = "../Test/"

# Add the directory containing your module to the Python path (wants absolute paths)

# Do the import
import MyModule