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.

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ best way to import a python file into your main
r/learnpython on Reddit: Best way to import a Python file into your main
March 16, 2024 -

So I am working with some old code I wrote and it occurred to me that I could clean things up by moving several functions defined in my single Python file to a "methods" file, where all of the functions written in the "methods" file would be accessible in "main". I am not sure what the best way to do this is. I have considered adding something like the following to "main":

import sys

import os

sys.path.append(os.path.abspath("C:\<file_path>"))

from <methods_file> import *

But I haven't had any luck. Any suggestions on an easy clean way to do this? Thanks in advance.

Discussions

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 do I import from a file in the current directory in Python 3? - Stack Overflow
In python 2 I can create a module like this: parent ->module ->__init__.py (init calls 'from file import ClassName') file.py ->class ClassName(obj) And this works. In python 3 I... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
how to import a file in python?
This is common, especially when multiple scripts use common funtions. Just be warned that if you change the function usage, you must change the script this is imported into to properly use your functions or classes. You can create mainline variable or statement, which are imported if you just do import mymodule. Just make sure your mainline variable do not interfere with your other variables. #This must exist within the same #project folder or the system PATH to just call it by name #No need to use the .py import MyCustomModule #If you only want a specific function from that module from MyCustomModule import functionname More on reddit.com
๐ŸŒ r/learnprogramming
6
1
November 11, 2022
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @vamsik23 โ€บ import-local-python-modules-a6e74950de4a
Import Local Python Modules. We all use modules in most of ourโ€ฆ | by vamsi | Medium
August 18, 2021 - Here we can see that I am adding folder_1 to python path using sys.path.append function so when I ask python to import some modules then it will check in folder_1 too. Please keep in mind to add whole path to the folder, donโ€™t use โ€œ~โ€ in the append path.
๐ŸŒ
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
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ reference โ€บ import.html
5. The import system โ€” Python 3.15.1 documentation
The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the import statement is defined as a call to the __import__() function, ...
๐ŸŒ
Quentin Fortier
fortierq.github.io โ€บ python-import
How to import local modules with Python - Quentin Fortier
May 9, 2021 - Python can indeed import c.d from this directory. This solution works regardless of the directory used to run Python: ~/Documents/code/project$ cd ../.. ~/Documents$ python3 code/project/src/a/b.py ['/home/qfortier/Documents/code/project/src/a', ..., 'code/project'] It should also work on a different computer, with a different filesystem or OS, thanks to Pathlib.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ modules.html
6. Modules โ€” Python 3.15.1 documentation
For example, the file sound/effects/__init__.py could contain the following code: ... This would mean that from sound.effects import * would import the three named submodules of the sound.effects package. Be aware that submodules might become shadowed by locally defined names.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Import Local Scripts | How to Import Modules in Python - YouTube
Learn how to import local scripts in other Python files as a module.-----------------------------------------------------------------------------------๐Ÿ’ฐDona...
Published: January 1, 2024
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-42497.html
Python 3.12 cannot import local python files as modules
July 25, 2024 - On a recent installation of Windows 10 I installed Python 3.12, things seemed to be working fine until I had difficulties importing other files. Which was weird considering I had no difficulties doing
๐ŸŒ
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).