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.

🌐
Python documentation
docs.python.org › 3 › reference › import.html
5. The import system — Python 3.15.1 documentation
Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace.
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
Import files directly from file location - Ideas - Discussions on Python.org
Importing new modules in Python is a pain, and far from straightforward. The trivial way to import a new module would be to give the full path of the file containing the required code - which could be a python __init__ module itself, setting up a fully functional module. More on discuss.python.org
🌐 discuss.python.org
0
July 25, 2023
How to import variable from parent __init__.py package?
the name app implicitly references the init module (as i understand and have experienced it), so saying from app import x will look in the init.py file for a lookup named x This assumes your python path points to the directory that "app" is located at, otherwise, you would need to do relative imports, but i'm not sure if or how you can go up two directories as it would seem you need too; let alone the fact that relative imports are icky (they're relative to the main module of the application, not the actual file system structure, so the highest you can go in the hierarchy is wherever the python execution began) More on reddit.com
🌐 r/learnpython
6
1
November 20, 2014
Tab delineated python 3 .txt file reading
With all due respect, I think you're way over-complicating this. The following is all you need to read the complete contents of a tab-delimited file without regard for naming the columns: from csv import reader data = [] with open('filename', newline='') as f: for row in reader(f, delimiter='\t'): data.append(row) That's it. data contains a list of lists, so data[0][0] is the first column of the first row, data[0][1] is the second column of the first row, data[0] is a list of all the columns in the first row, data[1][0] is the first column of the second row, and so on. You can do whatever you want with this very easily, for example to print the second column of every row: for row in data: print(row[1]) Or: print('\n'.join(row[1] for row in data)) To print the third column sorted: print('\n'.join(sorted(row[2] for row in data))) By the way, this is a waste of time: path = os.path.join(os.getcwd(), 'so.txt') If you open a bare filename (e.g. f = open('foobar.txt')) it will default to looking in the current working directory, so this getcwd() tedium is not doing anything useful. More on reddit.com
🌐 r/Python
5
2
March 29, 2012
🌐
Computer Science Atlas
csatlas.com › python-import-file-module
Python 3: Import Another Python File as a Module — Computer Science Atlas
Let's say we have two Python files in the same directory: ... The name used in the import statement is simply the module's filename without the .py extension at the end.
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › python-import-module-from-different-directory
Python – Import module from different directory - GeeksforGeeks
August 3, 2026 - # main.py import sys sys.path.insert(0, "../Folder_2") # add Folder_2 path to search list import module1 print(module1.add(5, 3)) # Output: 8 module1.odd_even(10) # Output: Even · Explanation: Here, sys.path.insert(0, "../Folder_2") tells Python where to look for module1.py. Instead of modifying code, you can set the PYTHONPATH environment variable, so Python knows where to look. ... For larger projects, the best way to organize code is by making folders into packages. A package is simply a folder that contains an __init__.py file (can be empty).
🌐
Penn Libraries
guides.library.upenn.edu › penntdm › python › import_files
Importing Files - Text Analysis - Guides at Penn Libraries
Python has a built-in json module to read JSON files. The read function is json.load() function, which takes a JSON file and returns a JSON dictionary. import json file = open('path-to-file') # Full path to the json file, or simply the file name # if the firle is in your current working directory json_file = json.load(file) # Returns JSON object as a dictionary
Find elsewhere
🌐
Python.org
discuss.python.org › ideas
Import files directly from file location - Ideas - Discussions on Python.org
July 25, 2023 - Importing new modules in Python is a pain, and far from straightforward. The trivial way to import a new module would be to give the full path of the file containing the required code - which could be a python __init__ m…
🌐
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
🌐
TechBeamers
techbeamers.com › how-to-import-another-python-file
Python Import File Tutorial - TechBeamers
November 30, 2025 - You can technically import everything from a file, but it’s generally not a good idea: # 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.
🌐
Python for the Lab
pythonforthelab.com › blog › complete-guide-to-imports-in-python-absolute-relative-and-more
Complete Guide to Imports in Python: Absolute, Relative, and More | Python For The Lab
If we have a file called module.py, we can simply use the following syntax to import it: ... In this case, sys is a module that belongs to the Python Standard Library. It provides functions to interact with the interpreter itself. For example, we can use it to find out if any arguments where passed while executing a script.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-import-local-modules-with-python
How to Import Local Modules with Python - GeeksforGeeks
July 23, 2025 - The __init__.py file in the modules directory makes it a package, allowing us to import modules using dot notation. Craft Python files (e.g., module1.py, module2.py) containing the code to reuse.
🌐
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.
🌐
Python-bloggers
python-bloggers.com › 2024 › 03 › import-simple-files-into-python
Import Simple Files into Python | Python-bloggers
March 1, 2024 - For our example, we will look at how to import csv files. Below is the code for how to complete this. import pandas as pd data=pd.read_csv('sample.csv') data.head() In line 1 of the code we load the pandas library as ‘pd’. In line 2, we use the read_csv() function to load our data into the ‘data’ object. Lastly, we use head() to take a peek at the first few lines of data. ... With this information, you now possess some basic knowledge on how to get data into Python for the purpose of being able to manipulate it.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-import-a-python-module-given-the-full-path
How to import a Python module given the full path? - GeeksforGeeks
July 23, 2025 - The Python module is a file consisting of Python code with a set of functions, classes, and variable definitions. The module makes the code reusable and easy to understand. The program that needs to use the module should import that particular module.
🌐
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
🌐
Real Python
realpython.com › absolute-vs-relative-python-imports
Absolute vs Relative Imports in Python – Real Python
May 9, 2026 - PEP 8, the official style guide for Python, has a few pointers when it comes to writing import statements. Here’s a summary: Imports should always be written at the top of the file, after any module comments and docstrings.
🌐
AskPython
askpython.com › python › built-in-methods › import-other-python-files
How Do I Import Other Python Files? - AskPython
May 25, 2023 - We defined the main function using the def keyword and then ran the main() function after that. When we executed the program we got the same output as before. The import statement is used to import another Python file or package into the file.
🌐
YouTube
youtube.com › watch
Importing Your Own Python Modules Properly - YouTube
Today we learn how to properly import your own Python modules and also what the __init__.py file is about.◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾📚 Programming Books & Merch 📚🐍 ...
Published: July 6, 2022