How can I import other Python files?
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:
-
Put this in /home/el/foo/fox.py:
def what_does_the_fox_say(): print("vixens cry")
-
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:
-
Put this in /home/el/foo2/mylib.py:
def moobar(): print("hi")
-
Put this in /home/el/foo2/main.py:
execfile("/home/el/foo2/mylib.py") moobar()
-
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:
-
Put this in /home/el/foo3/chekov.py:
def question(): print "where are the nuclear wessels?"
-
Put this in /home/el/foo3/main.py:
from chekov import question question()
-
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
-
Put this in /home/el/foo4/stuff/riaa.py:
def watchout(): print "computers are transforming into a noose and a yoke for humans"
-
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()
-
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:
- Make a new directory
/home/el/foo5/
- Make a new directory
/home/el/foo5/herp
-
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
Make a new directory /home/el/foo5/herp/derp
-
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
-
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!!"
-
The moment of truth, Make the new file
/home/el/foo5/main.py
, put this in there;from herp.derp.yolo import skycake skycake()
-
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 fileB.py
, you used the syntaximport module_name
. - In the second case,
folder
is the package that contains the moduleA.py
, you used the syntaximport 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
Tamer
Updated on March 25, 2022Comments
-
Tamer over 2 years
How do I import other files in Python?
- How exactly can I import a specific Python file, like
import file.py
? - How can I import a folder instead of a specific file?
- I want to load a Python file dynamically at runtime, based on user input.
- 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 getgap
fromextra.py
?-
dreftymac about 8 yearsSee Also: stackoverflow.com/questions/8663076/…
-
Shivam Jha almost 4 yearsIf 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 usefrom current_directory_name import *
, orfrom current_directory_name import THINGS_YOU_WANT_TO_IMPORT
. Play around a little bit for importing from different directory
- How exactly can I import a specific Python file, like
-
CornSmith almost 11 yearsIf you add an
import filename
to the init.py then you can import the module directly as the folder name. -
oriadam over 8 yearsYou should also add Example 6: using
__import__(py_file_name)
. Amazing guide anyway -
dgBP over 8 yearsEvery 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 over 8 yearsfrom
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 almost 8 yearsWhat'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 almost 8 yearsHey 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 over 7 yearsGood answer but the fact that you use a different import file as example all the times makes it cumbersome to read.
-
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 about 7 yearsWhat if I want a relative path?
-
supreme almost 7 years@GhostCat I have updated my response. thanks for the link "it would be preferable".
-
GhostCat almost 7 yearsAnd understand that not everyone is living in your timezone.
-
Royi over 6 yearsHow 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 over 6 yearsI 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 almost 6 yearsWhat if it's not a package but just a script file?
-
Alex Hall almost 6 yearsFor 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 over 5 yearsIs it still accurate in 2019? Is it python3 or 2?
-
tera_789 over 5 yearsExample 4 creates a file with
.pyc
ending. Who knows how to prevent it from being created? Or it is necessary? -
Benj about 5 yearsWouldn't
import DoStuff.py as DS
attempt to importpy
fromDoStuff
? -
Justin about 5 yearsI tried with a little variation and it worked.
from folder_a.script import *
Script.py is under the folder a. -
Umar.H about 5 yearsyour 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 about 5 yearsHow is making a new function better than using the function directly?
-
qwr about 5 yearsYou 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 about 5 yearsYou should've posted the contents of Mike Grouchy's post, especially since the link now 404s. web.archive.org/web/20190309045451/https://mikegrouchy.com/blog/…
-
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 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 almost 5 yearsImporting 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 over 4 years+1 This is what I was looking for. Couldn't understand other answers but you explained it using the directories.
-
bytedev over 4 yearsWhat if I want to import a py file that is in the parent directory?
-
Bohao LI over 4 years@bytedev Add
import sys
andsys.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 over 4 yearsWorked perfectly for me. In my example, I replaced:
from mypath import Path
withPath = callfunc("/folder/to/mypath.py", "Path")
. Thanks @Xiao-FengLi -
Tom over 4 yearsMy 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 over 4 yearsit was that. I was doing import file.py. Thanks!
-
blizz about 4 yearsAlso want to add - it seems packages can't have a dash in the name :\
-
Shivam Jha almost 4 yearseven within the same directory, in python 3.x,
import A
will not work. We have to usefrom current_directory_name import *
, orfrom current_directory_name import THINGS_YOU_WANT_TO_IMPORT
-
Bohao LI almost 4 years@ShivamJha I have Python version 3.7.4, and
import A
works well in the case thatA.py
&B.py
are in the same folder. -
Shivam Jha almost 4 yearsthat's then cool for you bro, I am in 3.8.x and it didn't work for me tho.
-
Bohao LI almost 4 years@ShivamJha I've tested
python 3.8.3
and it still works (tested onubuntu
andmac
), 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 almost 4 yearsOkay, thank you @BohaoLI, I will check it out brother
-
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 almost 4 yearsI am in windows 8.1; I am using python-3.8.5-embed-amd64. but it is not working.
-
Bohao LI almost 4 years@Falaque I am in Windows 10.
-
Chaim Eliyah over 3 yearshow "importlib" won over this answer, I will never know
-
Giuseppe almost 3 yearsTo 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 thePYTHONPATH
method (see this other answer) similar to example 4. -
Al G Johnston over 2 yearsCase 1 is not working for me. It is driving me nuts
-
mckenzm over 2 yearswhat if it does not have a .py extension ? It may be a common config file since var = "x" is commonly shared syntax.
-
mckenzm over 2 yearsThat'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 about 2 yearsLinux, Anaconda, Jupyter - not working.
-
Bohao LI about 2 years@HD2000 Could you please specify the error you encountered?