951

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
  • 27,818
  • 25
  • 108
  • 169
Tamer
  • 9,529
  • 3
  • 14
  • 4
  • 1
    See Also: http://stackoverflow.com/questions/8663076/python-best-way-to-add-to-sys-path-relative-to-the-current-running-script – dreftymac May 18 '16 at 22:10
  • 3
    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 – Shivam Jha Jul 01 '20 at 18:36

21 Answers21

1174

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

Eric Leschinski
  • 123,728
  • 82
  • 382
  • 321
  • 7
    You should also add Example 6: using `__import__(py_file_name)`. Amazing guide anyway – oriadam Dec 22 '15 at 02:59
  • 7
    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. – dgBP Feb 23 '16 at 07:23
  • 6
    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? – HelloGoodbye Aug 10 '16 at 08:58
  • 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... – dpat Sep 11 '16 at 10:28
  • 62
    Good answer but the fact that you use a different import file as example all the times makes it cumbersome to read. – gented Mar 21 '17 at 21:59
  • @ErikLeschinski, how would you classify and use 'subprocess' call method ? do you think it should be added along side with **method 6**? – garej Apr 02 '17 at 06:01
  • 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. – Royi Nov 11 '17 at 14:14
  • 4
    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** – radato Mar 05 '18 at 11:15
  • **Example 4** creates a file with `.pyc` ending. Who knows how to prevent it from being created? Or it is necessary? – tera_789 Jan 30 '19 at 00:47
  • 2
    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. – Umar.H Jun 07 '19 at 12:19
  • 1
    Also want to add - it seems packages can't have a dash in the name :\ – blizz Apr 23 '20 at 01:19
  • how "importlib" won over this answer, I will never know – Chaim Eliyah Feb 18 '21 at 18:56
501

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.

kiamlaluno
  • 24,790
  • 16
  • 70
  • 85
tabdulradi
  • 6,956
  • 1
  • 19
  • 32
  • 8
    If you add an `import filename` to the __init__.py then you can import the module directly as the folder name. – CornSmith Jul 22 '13 at 17:00
  • 10
    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.` – Tadhg McDonald-Jensen Feb 23 '16 at 15:04
  • 7
    What if it's not a package but just a script file? – Jonathan Jul 29 '18 at 02:19
  • 3
    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. – Alex Hall Aug 05 '18 at 14:05
  • 8
    Is it still accurate in 2019? Is it python3 or 2? – Sandburg Jan 24 '19 at 11:34
  • 5
    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! – Georg Aug 14 '19 at 22:19
  • it was that. I was doing import file.py. Thanks! – Orsu Feb 03 '20 at 23:56
83

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
James
  • 25,427
  • 16
  • 78
  • 101
  • 2
    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... – Tom Nov 26 '19 at 13:58
  • 1
    for me this was the best answer, concise and reproducable easily – El_1988 Nov 01 '20 at 19:11
47

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.

Bohao LI
  • 963
  • 14
  • 20
  • I tried with a little variation and it worked. `from folder_a.script import *` Script.py is under the folder a. – Justin May 29 '19 at 04:14
  • 2
    +1 This is what I was looking for. Couldn't understand other answers but you explained it using the directories. – Black Thunder Oct 07 '19 at 09:18
  • What if I want to import a py file that is in the parent directory? – bytedev Oct 16 '19 at 09:35
  • 1
    @bytedev Add `import sys` and `sys.path.append("..")` to the beginning of the file. According to this: https://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. – Bohao LI Oct 16 '19 at 09:46
  • 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` – Shivam Jha Jul 01 '20 at 18:35
  • @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. – Bohao LI Jul 02 '20 at 14:42
  • 1
    that's then cool for you bro, I am in 3.8.x and it didn't work for me tho. – Shivam Jha Jul 02 '20 at 19:46
  • @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. – Bohao LI Jul 02 '20 at 20:49
  • Okay, thank you @BohaoLI, I will check it out brother – Shivam Jha Jul 02 '20 at 20:51
  • @Falaque I've tested 3.8.5 on windows and it works. Just installed this version from Microsoft Store app on windows. – Bohao LI Aug 25 '20 at 20:05
  • I am in windows 8.1; I am using python-3.8.5-embed-amd64. but it is not working. – Falaque Aug 27 '20 at 07:10
  • @Falaque I am in Windows 10. – Bohao LI Aug 27 '20 at 17:20
35

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

iwasrobbed
  • 45,197
  • 20
  • 140
  • 190
Fatih Karatana
  • 2,140
  • 2
  • 27
  • 41
24

Import doc .. -- Link for reference

The __init__.py files are required to make Python treat the directories as containing packages, this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

__init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

mydir/spam/__init__.py
mydir/spam/module.py
import spam.module
or
from spam import module
Sanyal
  • 806
  • 9
  • 22
17
from file import function_name  ######## Importing specific function
function_name()                 ######## Calling function

and

import file              ######## Importing whole package
file.function1_name()    ######## Calling function
file.function2_name()    ######## Calling function

Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.

Devendra Bhat
  • 973
  • 1
  • 11
  • 19
16

If the function defined is in a file x.py:

def greet():
    print('Hello! How are you?')

In the file where you are importing the function, write this:

from x import greet

This is useful if you do not wish to import all the functions in a file.

Sid
  • 2,047
  • 1
  • 7
  • 24
6

the best way to import .py files is by way of __init__.py. the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

this post by Mike Grouchy is a great explanation of __init__.py and its use for making, importing, and setting up python packages.

supreme
  • 189
  • 2
  • 12
  • 2
    @GhostCat I have updated my response. thanks for the link "it would be preferable". – supreme Jun 27 '17 at 16:19
  • And understand that not everyone is living in your timezone. – GhostCat Jun 28 '17 at 04:07
  • 5
    You should've posted the contents of Mike Grouchy's post, especially since the link now 404s. https://web.archive.org/web/20190309045451/https://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html – qwr Jun 16 '19 at 03:51
5

How I import is import the file and use shorthand of it's name.

import DoStuff.py as DS
DS.main()

Don't forget that your importing file MUST BE named with .py extension

Luke359
  • 429
  • 6
  • 14
5

I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule. Imagine mymodule being layout like this:

/main.py
/mymodule
    /__init__.py
    /somefile.py
    /otherstuff.py

When loading somefile.py/otherstuff.py from __init__.py the contents should look like:

from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
Svend
  • 7,242
  • 3
  • 27
  • 43
4

There are couple of ways of including your python script with name abc.py

  1. e.g. if your file is called abc.py (import abc) Limitation is that your file should be present in the same location where your calling python script is.

import abc

  1. e.g. if your python file is inside the Windows folder. Windows folder is present at the same location where your calling python script is.

from folder import abc

  1. Incase abc.py script is available insider internal_folder which is present inside folder

from folder.internal_folder import abc

  1. As answered by James above, in case your file is at some fixed location

import os
import sys
scriptpath = "../Test/MyModule.py"
sys.path.append(os.path.abspath(scriptpath))
import MyModule

In case your python script gets updated and you don't want to upload - use these statements for auto refresh. Bonus :)

%load_ext autoreload 
%autoreload 2
rishi jain
  • 949
  • 1
  • 11
  • 21
2

You can also do this: from filename import something

example: from client import Client Note that you do not need the .py .pyw .pyui extension.

Benj
  • 518
  • 6
  • 17
2

In case the module you want to import is not in a sub-directory, then try the following and run app.py from the deepest common parent directory:

Directory Structure:

/path/to/common_dir/module/file.py
/path/to/common_dir/application/app.py
/path/to/common_dir/application/subpath/config.json

In app.py, append path of client to sys.path:

import os, sys, inspect

sys.path.append(os.getcwd())
from module.file import MyClass
instance = MyClass()

Optional (If you load e.g. configs) (Inspect seems to be the most robust one for my use cases)

# Get dirname from inspect module
filename = inspect.getframeinfo(inspect.currentframe()).filename
dirname = os.path.dirname(os.path.abspath(filename))
MY_CONFIG = os.path.join(dirname, "subpath/config.json")

Run

user@host:/path/to/common_dir$ python3 application/app.py

This solution works for me in cli, as well as PyCharm.

2

This is how I did to call a function from a python file, that is flexible for me to call any functions.

import os, importlib, sys

def callfunc(myfile, myfunc, *args):
    pathname, filename = os.path.split(myfile)
    sys.path.append(os.path.abspath(pathname))
    modname = os.path.splitext(filename)[0]
    mymod = importlib.import_module(modname)
    result = getattr(mymod, myfunc)(*args)
    return result

result = callfunc("pathto/myfile.py", "myfunc", arg1, arg2)
Xiao-Feng Li
  • 472
  • 5
  • 10
  • How is making a new function better than using the function directly? – qwr Jun 16 '19 at 03:43
  • @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"? – Xiao-Feng Li Jun 18 '19 at 01:37
  • Worked perfectly for me. In my example, I replaced: ``from mypath import Path`` with ``Path = callfunc("/folder/to/mypath.py", "Path")``. Thanks @Xiao-FengLi – user319436 Nov 24 '19 at 00:36
1

Just to import python file in another python file

lets say I have helper.py python file which has a display function like,

def display():
    print("I'm working sundar gsv")

Now in app.py, you can use the display function,

import helper
helper.display()

The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

Sundar Gsv
  • 527
  • 6
  • 5
1

This may sound crazy but you can just create a symbolic link to the file you want to import if you're just creating a wrapper script to it.

Jonathan
  • 5,179
  • 4
  • 41
  • 59
1

One very unknown feature of Python is the ability to import zip files:

library.zip
|-library
|--__init__.py

The file __init__.py of the package contains the following:

def dummy():
    print 'Testing things out...'

We can write another script which can import a package from the zip archive. It is only necessary to add the zip file to the sys.path.

import sys
sys.path.append(r'library.zip')

import library

def run():
    library.dummy()

run()
Farshid Ashouri
  • 11,423
  • 5
  • 40
  • 56
0

There are many ways, as listed above, but I find that I just want to import he contents of a file, and don't want to have to write lines and lines and have to import other modules. So, I came up with a way to get the contents of a file, even with the dot syntax (file.property) as opposed to merging the imported file with yours.
First of all, here is my file which I'll import, data.py

    testString= "A string literal to import and test with"


Note: You could use the .txt extension instead.
In mainfile.py, start by opening and getting the contents.

    #!usr/bin/env python3
    Data=open('data.txt','r+').read()

Now you have the contents as a string, but trying to access data.testString will cause an error, as data is an instance of the str class, and even if it does have a property testString it will not do what you expected.
Next, create a class. For instance (pun intended), ImportedFile

    class ImportedFile:

And put this into it (with the appropriate indentation):

    exec(data)


And finally, re-assign data like so:

    data=ImportedFile()

And that's it! Just access like you would for any-other module, typing print(data.testString) will print to the console A string literal to import and test with.
If, however, you want the equivalent of from mod import * just drop the class, instance assignment, and de-dent the exec.

Hope this helps:)
-Benji

Benj
  • 518
  • 6
  • 17
  • 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 Jun 16 '19 at 03:48
  • @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. – Benj Jun 16 '19 at 09:41
0
from y import * 
  • Say you have a file x and y.
  • You want to import y file to x.

then go to your x file and place the above command. To test this just put a print function in your y file and when your import was successful then in x file it should print it.

KSp
  • 731
  • 1
  • 5
  • 21
0

Using Python 3.5 or later, you can use importlib.util to directly import a .py file in an arbitrary location as a module without needing to modify sys.path.

import importlib.util
import sys

def load_module(file_name, module_name)
    spec = importlib.util.spec_from_file_location(module_name, file_name)
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module

The file_name parameter must be a string or a path-like object. The module_name parameter is required because all loaded Python modules must have a (dotted) module name (like sys, importlib, or importlib.util), but you can choose any available name you want for this new module.

You can use this function like this:

my_module = load_module("file.py", "mymod")

After it has been imported once into the Python process using the load_module() function, the module will be importable using the module name given to it.

# file.py =
print(f"{__name__} imported (file.py)")
# =========

# one.py ==
print(f"{__name__} imported (one.py)")
load_module("file.py", "mymod")
import two
# =========

# two.py ==
print(f"{__name__} imported (two.py)")
import mymod
# =========

Given the files above, you can run the following command to see how file.py became importable.

$ python3 -m one
__main__ imported (one.py)
two imported (two.py)
mymod imported (file.py)

This answer is based on the official Python documentation: importlib: Importing a source file directly.

palotasb
  • 3,223
  • 1
  • 18
  • 28