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/fox.py:

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

    el@apollo:/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 fox.py.

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/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

     el@apollo:/home/el/foo$ python main.py
     hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

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

     from chekov import question
     question()
    
  3. Run it like this:

     el@apollo:/home/el/foo3$ python main.py
     where are the nuclear wessels?
    

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

Example 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

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

     import sys
     import os
     sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
     from riaa import *
     watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py
    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 yourfile.py")

import os
os.system("python yourfile.py")

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

This example used to work for both Python 2 and Python 3, but now only works for Python 2. Python 3 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 Python 3, 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.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.pythonrc.py

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 main.py (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 main.py
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!
SKYCAKE!

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

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py 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 __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py 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/main.py, put this in there;

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

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk
    of men. SKYCAKE!!
    

    The empty __init__.py 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: https://stackoverflow.com/a/20753073/445131

Answer from Eric Leschinski on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › import-module-python
Import module in Python - GeeksforGeeks
April 25, 2026 - Python · import math pie = math.pi print("Value of pi:", pie) Output · Value of pi: 3.141592653589793 · Explanation: math module is imported using import math. We access the constant pi using math.pi and then the value is printed as part ...
🌐
Real Python
realpython.com › python-import
Python import: Advanced Techniques and Tips – Real Python
July 8, 2020 - Similarly, Python’s global namespace is also a dictionary. You can access it through globals(). It’s fairly common to import subpackages and submodules in an __init__.py file to make them more readily available to your users. You can see one example of this in the popular requests package.
🌐
Python documentation
docs.python.org › 3 › tutorial › modules.html
6. Modules — Python 3.15.2 documentation
From the surround module for example, you might use: from . import echo from .. import formats from ..filters import equalizer · Note that relative imports are based on the name of the current module’s package. Since the main module does not have a package, modules intended for use as the main module of a Python application must always use absolute imports.
🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.15.2 documentation
For example importlib.import_module() provides a recommended, simpler API than built-in __import__() for invoking the import machinery. Refer to the importlib library documentation for additional detail. Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else.
🌐
W3Schools
w3schools.com › python › python_modules.asp
Python Modules
Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not
🌐
DataCamp
datacamp.com › tutorial › modules-in-python
Python Modules Tutorial: Importing, Writing, and Using Them | DataCamp
June 1, 2026 - This means the print statement ... a module instead of importing everything. In the previous example, when you imported calculation into module_test.py both the add() and sub() functions were imported....
🌐
OpenClassrooms
openclassrooms.com › us › courses › 6900846-set-up-a-python-environment › 6989471-import-python-packages-and-modules
Import Python Packages and Modules - OpenClassrooms
For example, if you want to use the os module from the Python Standard Library to print the current working directory of a process, you could create a file called script.py with the following contents: ... In the script we import the entire ...
🌐
Mend
mend.io › blog › developer › python import: mastering the advanced features
Python Import: Mastering the Advanced Features
November 8, 2023 - Understanding how to import and utilize these modules effectively is a crucial skill for any Python developer. # Example of importing a module from the standard library import math # Using a function from the math module result = math.sqrt(25) print(result) # Output: 5.0
Find elsewhere
Top answer
1 of 16
1551

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/fox.py:

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

    el@apollo:/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 fox.py.

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/mylib.py:

    def moobar():
      print("hi")
    
  2. Put this in /home/el/foo2/main.py:

    execfile("/home/el/foo2/mylib.py")
    moobar()
    
  3. run the file:

     el@apollo:/home/el/foo$ python main.py
     hi
    

    The function moobar was imported from mylib.py and made available in main.py

Example 3, Use from ... import ... functionality:

  1. Put this in /home/el/foo3/chekov.py:

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

     from chekov import question
     question()
    
  3. Run it like this:

     el@apollo:/home/el/foo3$ python main.py
     where are the nuclear wessels?
    

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

Example 4, Import riaa.py if it's in a different file location from where it is imported

  1. Put this in /home/el/foo4/stuff/riaa.py:

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

     import sys
     import os
     sys.path.append(os.path.abspath("/home/el/foo4/stuff"))
     from riaa import *
     watchout()
    
  3. Run it:

    el@apollo:/home/el/foo4$ python main.py
    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 yourfile.py")

import os
os.system("python yourfile.py")

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

This example used to work for both Python 2 and Python 3, but now only works for Python 2. Python 3 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 Python 3, 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.

See: https://docs.python.org/2/library/user.html

Put this code into your home directory in ~/.pythonrc.py

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 main.py (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 main.py
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!
SKYCAKE!

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

Credit for this jist goes to: https://github.com/docwhat/homedir-examples/blob/master/python-commandline/.pythonrc.py 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 __init__.py under herp:

    el@apollo:/home/el/foo5/herp$ touch __init__.py
    el@apollo:/home/el/foo5/herp$ ls
    __init__.py
    
  4. Make a new directory /home/el/foo5/herp/derp

  5. Under derp, make another __init__.py file:

    el@apollo:/home/el/foo5/herp/derp$ touch __init__.py
    el@apollo:/home/el/foo5/herp/derp$ ls
    __init__.py
    
  6. Under /home/el/foo5/herp/derp make a new file called yolo.py 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/main.py, put this in there;

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

    el@apollo:/home/el/foo5$ python main.py
    SkyCake evolves to stay just beyond the cognitive reach of the bulk
    of men. SKYCAKE!!
    

    The empty __init__.py 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: https://stackoverflow.com/a/20753073/445131

2 of 16
561

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

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

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 __init__.py 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)
print(dir(pm))

Type help(__import__) for more details.

🌐
Career Karma
careerkarma.com › blog › python › python import statements: a guide
Python Import Statements: A Guide | Career Karma
December 1, 2023 - The import statement syntax is: import modulename. Python is accompanied by a number of built-in modules that allow you to perform common operations in your code. int(), for example, converts a value to an integer.
🌐
Python Morsels
pythonmorsels.com › 4-ways-import-module-python
4 ways to import a module in Python - Python Morsels
August 3, 2026 - The first way is to use the import ... looking up attributes on the math module object. For example, we can get the square root of a number by calling math.sqrt:...
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Import Modules, Packages, Functions in Python | note.nkmk.me
May 12, 2023 - For example, when you use import <module_name>, the Python interpreter first looks for a module with that name in the same directory as the currently executed script file.
🌐
Medium
medium.com › pythoneers › understanding-python-imports-types-usage-and-examples-e6460bd947fa
Understanding Python Imports: Types, Usage, and Examples | by Roopika J | The Pythoneers | Medium
January 1, 2025 - ModuleNotFoundError: Happens if the module isn’t installed or is unavailable in the Python environment. Fix: Ensure the module is installed using pip install module_name. This imports only specific functions, classes, or variables from a module.
🌐
Python
docs.python.org › 3 › library › importlib.html
importlib — The implementation of import
For example, consider the case of an import from foo.bar import _whiz, where _whiz is implemented with the binary module sources/foo/bar/_whiz.abi3.so, with sources being the location registered on sys.path, relative to the application bundle.
🌐
Programiz
programiz.com › python-programming › modules
Python Modules (With Examples)
August 21, 2024 - For example, # import only pi from math module from math import pi print(pi) # Output: 3.141592653589793 · Here, we imported only the pi attribute from the math module. In Python, we can import all names(definitions) from a module using the following construct:
🌐
Chris Yeh
chrisyeh96.github.io › 2017 › 08 › 08 › definitive-guide-python-imports.html
The Definitive Guide to Python import Statements | Chris Yeh
August 8, 2017 - For example, packB is a namespace package because it doesn’t have a __init__.py file in the folder. If we start a Python 3.6 interactive interpreter in the test/ directory, then we get the following output: >>> import packB >>> packB <module 'packB' (namespace)>
🌐
Medium
medium.com › @AlexanderObregon › how-pythons-import-system-works-ff2e410edf6b
How Python’s Import System Works | Medium
July 12, 2024 - In this example, .. goes up one level in the package hierarchy to the parent package (mypackage), and then imports module1 from it. When you import a module in Python, the interpreter follows a systematic approach to locate and load the module. This process involves searching through a series of directories defined in the search path.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › __import__.html
__import__ — Python Reference (The Right Way) 0.1 documentation
Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime. When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. For example, the statement import spam results in bytecode resembling the following code:
🌐
Codementor
codementor.io › community › a python import tutorial for beginners
A Python Import Tutorial for Beginners | Codementor
January 18, 2017 - Now open up a console and cd into your newly created working directory and launch the Python interpreter. Type in the statements below: print my_funcs # NameError import my_funcs # from this point on my_funcs is in the scope print my_funcs # prints information about the module my_funcs.print_a() # call the function print_a that is a member of the my_funcs module my_funcs.print_b()