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
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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-import-other-python-files
How to Import Other Python Files? - GeeksforGeeks
July 23, 2025 - The most straightforward way to import a Python file is by using the import statement.
Discussions

Importing a python file into another python file
Remove the first line and it might work. The sys.path thing tells "search at this directory for modules", and you need to import after it (as is being done) and not before it (as is also being done). Note that importing * is usually frowned upon, and instead it's usually better to import thing by thing. More on reddit.com
๐ŸŒ r/learnpython
12
1
July 9, 2024
How do I import other Python files?
Learn the different ways to reuse ... import, from ... import, and how to manage modules and paths effectively. Log in to share your answer and help other learners. Log in to answer ... Importing other Python files into your script is a great way to keep your code organized and reusable. Python makes this easy through its built-in module system. If you have functions or classes in another file, you ... More on janbasktraining.com
๐ŸŒ janbasktraining.com
2
May 11, 2025
Best way to import a Python file into your main
Been there, done that, not a good idea. If your "methods"-file is specific to this project, just restructure your project so that you can import it normally. If it isn't, turn it into a package, add it as a dependency, have it installed, and just import it. Don't use sys.path for this. More on reddit.com
๐ŸŒ r/learnpython
15
7
March 16, 2024
Importing python files from different folder
There's a few different ways and talking about the specifics on a Reddit comment gets difficult fast, but if project is a Python package you can do from project.files_2 import file_2 If project is the repository root and files_2 is a package, make sure that it's installed and just do from files_2 import file_2 As a fallback solution you can use sys.path.insert to make Python aware of the files you want to import, but it's not exactly clean and I'd strongly recommend the other solutions instead. If your project is a public repository, I recommend that you post a link here for us to give more specific help. More on reddit.com
๐ŸŒ r/learnpython
6
6
September 6, 2023
๐ŸŒ
Computer Science Atlas
csatlas.com โ€บ python-import-file-module
Python 3: Import Another Python File as a Module โ€” Computer Science Atlas
The name used in the import statement is simply the module's filename without the .py extension at the end. Python versions 3.3 and higher allow easy imports of modules in subdirectories of the current script's directory.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ importing a python file into another python file
r/learnpython on Reddit: Importing a python file into another python file
July 9, 2024 -

Hiya, so I've just recently started learning python by completing some challenges and one of them is to import the functions made in one python file to another so they can be tested. I'm trying to import this file but it keeps telling me there's no module by the name I'm putting in. I can't see any spelling mistakes in the file name and I believe I'm using the correct syntax and function so I don't know what the issue is. These are the things I've tried and the error message I keep getting.

(File I'm trying to import is called UnitTests.py)

attempt #1

import UnitTests  

attempt #2

from UnitTests import *  

attempt #3

import sys
sys.path.append(
    'coding/python/boot.dev/Ch. 5: Testing + Debugging')
from UnitTests import * 

Error message

Traceback (most recent call last):   
File "<stdin>", line 1, in <module>   
ModuleNotFoundError: No module named 'UnitTests'

SEMI-RESOLVED?

After adding the specific function I wanted it to run the script can now use the function (called total_xp)

from UnitTests import total_xp

The code as a whole is working now and that's the important part but the semi-unresolved bit for me is if I run just the line from UnitTests import total_xp it once again says the file UnitTests doesn't exist and I was wondering why that is? My friend said it may be because running the whole script it knows which directory itself is in but just running the single line is just running the command and therefore it doesn't know where to find it, but this also doesn't make sense to me because on my third attempt I told it where the directory was and it still didn't work. Again it's not super important because you'd never import the file to another script if you're not going to use a function from said file, it's more out of curiosity now that I want to know why I can't just run it as a single line.

๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-can-i-source-a-python-file-from-another-python-file
How can I source a Python file from another Python file?
April 17, 2025 - The import statement is the most common way to include external Python files or modules in your script. ... # main.py import math_operations result = math_operations.add(5, 4) print(result) result = math_operations.subtract(10, 6) print(result) ...
๐ŸŒ
AskPython
askpython.com โ€บ python โ€บ built-in-methods โ€บ import-other-python-files
How Do I Import Other Python Files? - AskPython
May 25, 2023 - The import statement is used to import another Python file or package into the file. It is a form of inheritance that is one of the property of Object Oriented Programming language. You can even import a particular function or class from a file.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How To Import One Python File Into Another - YouTube
How to import files in python. You can import python classes and functions from other .py files in the same directory.Source Code:https://github.com/ImKennyY...
Published: May 12, 2021
Find elsewhere
๐ŸŒ
Better Stack
betterstack.com โ€บ community โ€บ questions โ€บ importing-files-from-different-folders-python
Importing files from different folder in Python? | Better Stack Community
Alternatively, you can use the PYTHONPATH environment variable to add the path to the folder containing the file you want to import. You can also use the importlib.import_module() function to import modules from different folders by providing the full path of the module.
๐ŸŒ
MLJAR
mljar.com โ€บ answers โ€บ import-files-from-different-folder-python
Import files from different folder in Python
To import functions from main.py into file2.py, that is import from parent directory, you can use the following code: ... You must call file2.py using -m (module) syntax. Run the following command from the parent directory of application:
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ import files from a different folder in python
Python Import From Parent Directory and Subfolders | Sentry
Import modules from parent, child, and sibling directories using package relative imports with __init__.py or by adding paths to sys.path at runtime
๐ŸŒ
Medium
medium.com โ€บ geekculture โ€บ how-to-import-another-file-in-python-4f833ea462b1
How to Import Another File in Python? | by Shuai Li | Geek Culture | Medium
November 29, 2021 - How to Import Another File in Python? Itโ€™s really a troublesome problem. Splitting code into different files is really important for a large project. But when I tried to modulize code in Python, I โ€ฆ
๐ŸŒ
TechBeamers
techbeamers.com โ€บ how-to-import-another-python-file
Python Import File Tutorial - TechBeamers
November 30, 2025 - # main.py from math import * result_add = add(5, 3) While this does the job, itโ€™s not recommended because it can make your code messy and lead to problems. When your Python files are in the same project, you can use relative imports. Consider a project structure like this: ... This helps import another Python file within your project without making the code confusing.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-import-one-Python-file-to-another
How to import one Python file to another - Quora
Answer (1 of 3): if you have the main python file in which you want to import any other python file, then first of all it is advised to keep both of the files in the same location. After that is done simply import the other file by writing: import .py is not needed after the file nam...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-import-variables-from-another-file-in-python
How to import variables from another file in Python? - GeeksforGeeks
July 23, 2025 - To import variables from another file in Python, you need to use the import statement. By importing a file, you gain access to its variables and functions. This can be done by simply using import filename or from filename import variable_name ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-import-other-python-files
How to import other Python files?
May 31, 2024 - You create a new Python script in the same directory as math_operations.py. Then you use the import keyword followed by the name of the module without the .py extension. In this case, it would be import math_operations.
๐ŸŒ
GitHub
gist.github.com โ€บ MRobertEvers โ€บ 55a989b4883ea8d7715d2e156627f034
Import Python Files From Another Directory Python 3 ยท GitHub
Since Python will search sys.path when it reaches an import module instruction, we can include the path to that module in sys.path before calling the import. Given a folder structure like this ... This method is inspired by Section 6.4 of the Python docs. It states that the presence of an __init__.py file (may be empty) will cause python to treat the directory it is in as a Package.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ reference โ€บ import.html
5. The import system โ€” Python 3.15.1 documentation
Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way.
๐ŸŒ
YouTube
youtube.com โ€บ teachingcs
Python For Beginners - Importing Functions From Another File Explained - YouTube
00:00 - Start00:17 - Why you should modularise your code01:04 - How to make a new module02:17 - Importing functions from another file03:15 - Import just a sp...
Published: July 31, 2022
Views: 8K
๐ŸŒ
JanBask Training
janbasktraining.com โ€บ community โ€บ python โ€บ how do i import other python files?
How do I import other Python files? | JanBask Training Community
May 11, 2025 - Learn the different ways to reuse code from other Python files using import, from ... import, and how to manage modules and paths effectively. Log in to share your answer and help other learners. Log in to answer ... Importing other Python files into your script is a great way to keep your code organized and reusable. Python makes this easy through its built-in module system. If you have functions or classes in another file, you can bring them into your current file with just a few lines of code.
๐ŸŒ
CodeRivers
coderivers.org โ€บ blog โ€บ python-import-from-another-file
Python Import from Another File: A Comprehensive Guide - CodeRivers
July 21, 2026 - Relative imports (using dots like from . import module) only work within packages. They do not work when running a file directly as a script. Either run the module as part of a package using python -m package.module or switch to absolute imports. Importing from another file in Python is a crucial aspect of modular programming.