MyTetra Share
Делитесь знаниями!
How to import other Python files?
Время создания: 13.07.2018 15:30
Текстовые метки: python import py
Раздел: Python
Запись: Velonski/mytetra-database/master/base/1531285964p3abzei1he/text.html на

How do I import other files in Python?

How exactly can I import a specific python file like import

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 I have:

from extra import *

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

def gap():



What do I add to the import statement to just get gap from

python python-import

shareimprove this question

edited May 16 at 7:24



asked Feb 28 '10 at 3:40



See Also:… – dreftymac May 18 '16 at 22:10

add a comment

11 Answers

active oldest votes

up vote


down vote


importlib is recent addition in Python to programmatically import a module. It just a wrapper around __import__ See

import importlib

moduleName = input('Enter module name:')


Update: Answer below is outdated. Use the more recent alternative above.

Just import file without the '.py' extension.

You can mark a folder as a package, by adding an empty file named

You can use the __import__ function. It takes the module name as a string. (Again: module name without the '.py' extension.)

pmName = input('Enter module name:')

pm = __import__(pmName)


Type help(__import__) for more details.

shareimprove this answer

edited Feb 16 at 14:06



answered Feb 28 '10 at 3:42




If you add an import filename to the then you can import the module directly as the folder name. – CornSmith Jul 22 '13 at 17:00


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

add a comment

up vote


down vote

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/

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

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/

def moobar():


Put this in /home/el/foo2/



run the file:

el@apollo:/home/el/foo$ python


The function moobar was imported from and made available in

Example 3, Use from ... import ... functionality:

Put this in /home/el/foo3/

def question():

print "where are the nuclear wessels?"

Put this in /home/el/foo3/

from chekov import question


Run it like this:

el@apollo:/home/el/foo3$ python

where are the nuclear wessels?

If you defined other functions in, they would not be available unless you import *

Example 4, Import if it's in a different file location from where it is imported

Put this in /home/el/foo4/stuff/

def watchout():

print "computers are transforming into a noose and a yoke for humans"

Put this in /home/el/foo4/

import sys

import os


from riaa import *


Run it:

el@apollo:/home/el/foo4$ python

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")

import os


Example 6, import your file via piggybacking the python startuphook:


Put this code into your home directory in ~/

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 (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:

$ python

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!


Credit for this jist goes to: 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 under herp:

el@apollo:/home/el/foo5/herp$ touch

el@apollo:/home/el/foo5/herp$ ls

Make a new directory /home/el/foo5/herp/derp

Under derp, make another file:

el@apollo:/home/el/foo5/herp/derp$ touch

el@apollo:/home/el/foo5/herp/derp$ ls

Under /home/el/foo5/herp/derp make a new file called 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/, put this in there;

from herp.derp.yolo import skycake


Run it:

el@apollo:/home/el/foo5$ python

SkyCake evolves to stay just beyond the cognitive reach of the bulk

of men. SKYCAKE!!

The empty 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:

Bonus protip

whether you are using Mac, Linux or Windows, you need to be using python's idle editor as described here. It will unlock your python world.

shareimprove this answer

edited Oct 14 '17 at 17:15

answered Dec 23 '13 at 18:46

Eric Leschinski



You should also add Example 6: using __import__(py_file_name). Amazing guide anyway – oriadam Dec 22 '15 at 2:59


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 7:23


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 8: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


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

show 3 more comments

up vote


down vote

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)


# Do the import

import MyModule

shareimprove this answer

edited Sep 13 '14 at 12:44

answered Apr 30 '13 at 12:30



add a comment

up vote


down vote

You do not have many complex methods to import a python file from one folder to another. Just create a 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

shareimprove this answer

edited Feb 24 '16 at 23:02



answered Jan 24 '13 at 14:08

Fatih Karatana



What if I want a relative path? – domih Jun 2 '17 at 9:22

add a comment

up vote


down vote

Import doc ..

The 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. can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.



import spam.module


from spam import module

shareimprove this answer

edited Nov 19 '16 at 9:17

Max Alibaev


answered Oct 2 '15 at 8:27



add a comment

up vote


down vote

from file import function_name ######## Importing specific function

function_name() ######## Calling function


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 which you want to import as a library is present in your current directory only.

shareimprove this answer

edited Feb 16 at 19:49

answered Feb 9 at 18:49

Devendra Bhat


add a comment

up vote


down vote

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

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

shareimprove this answer

edited Jun 27 '17 at 16:14

answered Jun 27 '17 at 15:43




@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 4:07

add a comment

up vote


down vote

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

import as DS


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

shareimprove this answer

answered May 9 '16 at 9:01



add a comment

up vote


down vote

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:






When loading from the contents should look like:

from mymodule.somefile import somefunc

from mymodule.otherstuff import otherfunc

shareimprove this answer

edited Apr 28 at 17:19

answered Apr 18 at 9:51



add a comment

up vote


down vote

Just to import python file in another python file

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

def display():

print("I'm working sundar gsv")

Now in, you can use the display function,

import helper


The output,

I'm working sundar gsv

NOTE: No need to specify the .py extension.

Так же в этом разделе:
MyTetra Share v.0.58
Яндекс индекс цитирования