How can I import other Python files?

2,318,403

Solution 1

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.

Solution 2

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:

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.

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 python3, 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

Solution 3

First case

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

. 
├── A.py 
└── B.py

You can do this in file B.py:

import A

or

from A import *

or

from A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Second case

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

.
├── B.py
└── folder
     └── A.py

You can do this in file B.py:

import folder.A

or

from folder.A import *

or

from folder.A import THINGS_YOU_WANT_TO_IMPORT_IN_A

Then you will be able to use all the functions of file A.py in file B.py


Summary

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

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

Solution 4

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)
sys.path.append(os.path.abspath(scriptpath))

# Do the import
import MyModule

Solution 5

You do not have many complex methods to import a python file from one folder to another. Just create a __init__.py file to declare this folder is a python package and then go to your host file where you want to import just type

from root.parent.folder.file import variable, class, whatever

Share:
2,318,403
Tamer
Author by

Tamer

Updated on March 25, 2022

Comments

  • Tamer
    Tamer over 2 years

    How do I import other files in Python?

    1. How exactly can I import a specific Python file, like import file.py?
    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 input.
    4. I want to know how to load just one specific part from the file.

    For example, in main.py I have:

    from extra import *
    

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

    def gap():
        print
        print
    

    What do I add to the import statement to just get gap from extra.py?

    • dreftymac
      dreftymac about 8 years
    • Shivam Jha
      Shivam Jha almost 4 years
      If A and B are two files within the same directory, in python 3.x, and you want to import A's content, import A will not work. We have to use from current_directory_name import *, or from current_directory_name import THINGS_YOU_WANT_TO_IMPORT . Play around a little bit for importing from different directory
  • CornSmith
    CornSmith almost 11 years
    If you add an import filename to the init.py then you can import the module directly as the folder name.
  • oriadam
    oriadam over 8 years
    You should also add Example 6: using __import__(py_file_name). Amazing guide anyway
  • dgBP
    dgBP over 8 years
    Every time I have an import issue I end up at this question and am always able to solve my problem. If I could upvote this for each time you've helped me, I would.
  • Tadhg McDonald-Jensen
    Tadhg McDonald-Jensen over 8 years
    from help(__import__): Because this function is meant for use by the Python interpreter and not for general use it is better to use importlib.import_module() to programmatically import a module.
  • HelloGoodbye
    HelloGoodbye almost 8 years
    What's the big difference between all of these, and why is one better than any other? For example 5, you write "Import files in python with the bare import command," but you also use the (bare?) import command in examples 1, 3 and 4, don't you?
  • dpat
    dpat almost 8 years
    Hey Eric! I think you got me wrong.. I just wanted to answer HelloGoodbyes question "what's the big difference between all of these" because I too was curious and found the blog entry (which is NOT mine btw) which I thought was helpful for him too...
  • gented
    gented over 7 years
    Good answer but the fact that you use a different import file as example all the times makes it cumbersome to read.
  • garej
    garej about 7 years
    @ErikLeschinski, how would you classify and use 'subprocess' call method ? do you think it should be added along side with method 6?
  • domih
    domih about 7 years
    What if I want a relative path?
  • supreme
    supreme almost 7 years
    @GhostCat I have updated my response. thanks for the link "it would be preferable".
  • GhostCat
    GhostCat almost 7 years
    And understand that not everyone is living in your timezone.
  • Royi
    Royi over 6 years
    How about having a file which just imports and loads all necessary packages. How could one do that and make the current file aware of all loaded in the other file? Thank You.
  • radato
    radato over 6 years
    I would like to emphasize that even if you work on Windows, the import is case sensitive. So you cannot have Module.py and have in your code import module
  • Jonathan
    Jonathan almost 6 years
    What if it's not a package but just a script file?
  • Alex Hall
    Alex Hall almost 6 years
    For importing a script file in the same path (maybe it would also work for a script file in a Python search path), import filenamenoext works just fine for me, with Python 3.4.8.
  • Sandburg
    Sandburg over 5 years
    Is it still accurate in 2019? Is it python3 or 2?
  • tera_789
    tera_789 over 5 years
    Example 4 creates a file with .pyc ending. Who knows how to prevent it from being created? Or it is necessary?
  • Benj
    Benj about 5 years
    Wouldn't import DoStuff.py as DS attempt to import py from DoStuff?
  • Justin
    Justin about 5 years
    I tried with a little variation and it worked. from folder_a.script import * Script.py is under the folder a.
  • Umar.H
    Umar.H about 5 years
    your opening statement should be a precursor to every popular answer, thanks for this, my analytical code base is a mess, refactoring for the first time.
  • qwr
    qwr about 5 years
    How is making a new function better than using the function directly?
  • qwr
    qwr about 5 years
    You seriously think reading the contents of the file as a string and then executing it is a good solution when we have all the other solutions people have posted?
  • qwr
    qwr about 5 years
    You should've posted the contents of Mike Grouchy's post, especially since the link now 404s. web.archive.org/web/20190309045451/https://mikegrouchy.com/b‌​log/…
  • Benj
    Benj about 5 years
    @qwr Erm yes, I do. Many of the other answers don't work in some situations. Which is why I needed an easy way that was guaranteed to work. If you are incapable of seeing things from anothers point of view, you need to try using the official IDLE.
  • Xiao-Feng Li
    Xiao-Feng Li about 5 years
    @qwr The new function callfunc() is simply a wrapper of the code to call the target function in the python file dynamically. The example given is the target "myfunc" in the python file "pathto/myfile.py". What do you mean by "using the function directly"?
  • Georg
    Georg almost 5 years
    Importing in Python is a bizarre mess. It should be possible to import any function from any file, with a simple line of code providing the path (absolute or relative, hard-coded or stored in a variable) to the file. Python, just do it!
  • Black Thunder
    Black Thunder over 4 years
    +1 This is what I was looking for. Couldn't understand other answers but you explained it using the directories.
  • bytedev
    bytedev over 4 years
    What if I want to import a py file that is in the parent directory?
  • Bohao LI
    Bohao LI over 4 years
    @bytedev Add import sys and sys.path.append("..") to the beginning of the file. According to this: stackoverflow.com/a/48341902/6057480 . Tested, working perfectly, after doing this, you will be able to import a py file in the parent directory and still able to import py files in the same directory and sub-directories.
  • user319436
    user319436 over 4 years
    Worked perfectly for me. In my example, I replaced: from mypath import Path with Path = callfunc("/folder/to/mypath.py", "Path"). Thanks @Xiao-FengLi
  • Tom
    Tom over 4 years
    My friend checked this today with no luck - looks like filename should not be there. He used local file in parent directory and "./" worked at the end as if parent directory (..). Fixing problem in post was rejected - probably misunderstanding(?) Print sys.path and compare records if you are not sure...
  • Orsu
    Orsu over 4 years
    it was that. I was doing import file.py. Thanks!
  • blizz
    blizz about 4 years
    Also want to add - it seems packages can't have a dash in the name :\
  • Shivam Jha
    Shivam Jha almost 4 years
    even within the same directory, in python 3.x, import A will not work. We have to use from current_directory_name import *, or from current_directory_name import THINGS_YOU_WANT_TO_IMPORT
  • Bohao LI
    Bohao LI almost 4 years
    @ShivamJha I have Python version 3.7.4, and import A works well in the case that A.py & B.py are in the same folder.
  • Shivam Jha
    Shivam Jha almost 4 years
    that's then cool for you bro, I am in 3.8.x and it didn't work for me tho.
  • Bohao LI
    Bohao LI almost 4 years
    @ShivamJha I've tested python 3.8.3 and it still works (tested on ubuntu and mac), which can confirm that this problem is not a version issue, read the error message may help. Though I don't know why it doesn't work for you.
  • Shivam Jha
    Shivam Jha almost 4 years
    Okay, thank you @BohaoLI, I will check it out brother
  • Bohao LI
    Bohao LI almost 4 years
    @Falaque I've tested 3.8.5 on windows and it works. Just installed this version from Microsoft Store app on windows.
  • Falaque
    Falaque almost 4 years
    I am in windows 8.1; I am using python-3.8.5-embed-amd64. but it is not working.
  • Bohao LI
    Bohao LI almost 4 years
    @Falaque I am in Windows 10.
  • Chaim Eliyah
    Chaim Eliyah over 3 years
    how "importlib" won over this answer, I will never know
  • Giuseppe
    Giuseppe almost 3 years
    To tend towards a more complete list of solutions, I think we could add the following two interactive methods: the python -m method (see this answer) similar to example 1, and the PYTHONPATH method (see this other answer) similar to example 4.
  • Al G Johnston
    Al G Johnston over 2 years
    Case 1 is not working for me. It is driving me nuts
  • mckenzm
    mckenzm over 2 years
    what if it does not have a .py extension ? It may be a common config file since var = "x" is commonly shared syntax.
  • mckenzm
    mckenzm over 2 years
    That's a deal breaker. In the extreme I will be embedding PHP to import now, I don't really need to just import def's. I may want to import "dev only" tracts or common app.cfg files. I just want to be able to substitute code. Preprocessing it in is a rotten way to do it.
  • HD2000
    HD2000 about 2 years
    Linux, Anaconda, Jupyter - not working.
  • Bohao LI
    Bohao LI about 2 years
    @HD2000 Could you please specify the error you encountered?