787

file.py contains a function named function. How do I import it?

from file.py import function(a,b)

The above gives an error:

ImportError: No module named 'file.py'; file is not a package

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
user2977230
  • 8,897
  • 5
  • 14
  • 9
  • 106
    `from file import function`. No need for file extensions or function parameters – samrap Dec 01 '13 at 06:35
  • 11
    You should probably go through the [modules section](http://docs.python.org/2/tutorial/modules.html) in the Python tutorial. – Burhan Khalid Dec 01 '13 at 06:51
  • 1
    Also if you want to import the function from the `file.py`, make sure there is no package in your directory with the name `file`. – SomeBruh Apr 23 '20 at 00:04
  • If you have an ImportError or a ModuleError see this question, it was very helpful for me https://stackoverflow.com/questions/31279446/import-error-no-module-named-xxxx/33615230#33615230 – Sunchock Aug 10 '21 at 23:28
  • `from your_file_name import *` works for me – Doğaç Mar 06 '23 at 19:37

19 Answers19

817

First, import function from file.py:

from file import function

Later, call the function using:

function(a, b)

Note that file is one of Python's core modules, so I suggest you change the filename of file.py to something else.

Note that if you're trying to import functions from a.py to a file called b.py, you will need to make sure that a.py and b.py are in the same directory.

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 10
    The "file" was just a placeholder for the question I am asking, not the actual file name. Thank you though. I will try this and get back to you. – user2977230 Dec 01 '13 at 06:37
  • 8
    I tried this, but it is still showing the error: Has it got anything to do with Python 3, or is a general problem? – DarkRose Jun 29 '15 at 07:02
  • 13
    @GamesBrainiac, what if the file you want to import functions from is in a different directory? Can I include the filepath preceeding the filename, or is there something more complicated? – Tom Apr 27 '16 at 01:14
  • 11
    @Tom You have to add that path to the PYTHONPATH variable if it is not already in there. – Games Brainiac Apr 27 '16 at 12:20
  • 33
    Is there a way to import functions from a.py to a file b.py if they are not in the same directory? – Nirvan Sengupta Sep 27 '16 at 22:50
  • newbies try "import file", which should execute only once (singleton) – Jason May 14 '17 at 02:22
  • Do you have to import all dependencies from `file` that are used in `function` as well? – quantik Jul 05 '17 at 21:03
  • In Python 2 it looks like this either (a) executes the entire script you're referencing with `from foo import ...` or (b) does not work if `foo.py` has references to the `argparse` library. – alex Mar 01 '18 at 16:50
  • @DarkRose Same for me, I fixed it by changing the order of the imports within __init__.py file, making sure root dependencies were loaded after their transitive dependencies. – nuKs Apr 07 '21 at 06:21
  • Didn't work with a hyphen in the filename, e.g. `from fil-e import *`. – PatrickT Jan 04 '22 at 07:28
  • For those coming from a javascript background, note that you don't need quotes around the file name in the import. Also, if it's in a different directory, you can do `from myDirectory.someSubDirectory.myFile import yay`. – JohnnyFun Aug 30 '23 at 15:43
297

Do not write .py when importing.

Let file_a.py contain some functions inside it:

def f():
  return 1

def g():
  return 2

To import these functions into file_z.py, do this:

from file_a import f, g
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
109

If your file is in the different package structure and you want to call it from a different package, then you can call it in that fashion:

Let's say you have following package structure in your python project:

Python package and file structure

in - com.my.func.DifferentFunction python file you have some function, like:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

And you want to call different functions from Example3.py, then following way you can do it:

Define import statement in Example3.py - file for import all function

from com.my.func.DifferentFunction import *

or define each function name which you want to import

from com.my.func.DifferentFunction import add, sub, mul

Then in Example3.py you can call function for execute:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

Output:

 add :  30

 sub :  10

 mul :  200
abanmitra
  • 1,344
  • 1
  • 10
  • 10
97

Method 1. Import the specific function(s) you want from file.py:

from file import function

Method 2. Import the entire file:

import file as fl

Then, to call any function inside file.py, use:

fl.function(a, b)
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Pulkit Bansal
  • 1,963
  • 14
  • 12
51

You can call the function from a different directory as well, in case you cannot or do not want to have the function in the same directory you are working. You can do this in two ways (perhaps there are more alternatives, but these are the ones that have worked for me).

Alternative 1 Temporarily change your working directory

import os

os.chdir("**Put here the directory where you have the file with your function**")

from file import function

os.chdir("**Put here the directory where you were working**")

Alternative 2 Add the directory where you have your function to sys.path

import sys

sys.path.append("**Put here the directory where you have the file with your function**")

from file import function
Juan Ossa
  • 1,153
  • 1
  • 10
  • 14
39

To fix

ModuleNotFoundError: No module named

try using a dot (.) in front of the filename to do a relative import:

from .file import function
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Ricky Boy
  • 723
  • 7
  • 7
38

Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:

from directory_name.file_name import function_name

And later be used: function_name()

Weky
  • 670
  • 8
  • 6
17

Rename the module to something other than 'file'.

Then also be sure when you are calling the function that:

1)if you are importing the entire module, you reiterate the module name when calling it:

import module
module.function_name()

or

import pizza
pizza.pizza_function()

2)or if you are importing specific functions, functions with an alias, or all functions using *, you don't reiterate the module name:

from pizza import pizza_function
pizza_function()

or

from pizza import pizza_function as pf
pf()

or

from pizza import *
pizza_function()
misterrodger
  • 216
  • 2
  • 8
  • This is the best answer as it details how to import a file FULL of functions, and how to call them. – Dave Dec 13 '22 at 20:11
14

First save the file in .py format (for example, my_example.py). And if that file have functions,

def xyz():

        --------

        --------

def abc():

        --------

        --------

In the calling function you just have to type the below lines.

file_name: my_example2.py

============================

import my_example.py


a = my_example.xyz()

b = my_example.abc()

============================

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nagaraj Simpi
  • 141
  • 1
  • 5
  • 2
    I don't know if my fail is about python versions. What i do choosing this example is `import fn` (without extension) and using them directly on the main file `fn.my_funcion()`. When i use `import fn.py` tries to load py.py file, wich doesn't exist. Using `from fn.py import funcname` didn't work too. Thank you. – m3nda Jun 09 '15 at 04:01
10

append a dot . in front of a file name if you want to import this file which is in the same directory where you are running your code.

For example, I'm running a file named a.py and I want to import a method named addFun which is written in b.py, and b.py is there in the same directory

from .b import addFun
JoSSte
  • 2,953
  • 6
  • 34
  • 54
Shravan Kumar
  • 241
  • 1
  • 3
  • 6
9

Inside MathMethod.Py.

def Add(a,b):
   return a+b 

def subtract(a,b):
  return a-b

Inside Main.Py

import MathMethod as MM 
  print(MM.Add(200,1000))

Output:1200

Mahabubuzzaman
  • 349
  • 3
  • 3
6

You don't have to add file.py.

Just keep the file in the same location with the file from where you want to import it. Then just import your functions:

from file import a, b
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohan
  • 145
  • 2
  • 8
6

Solution1: In one file myfun.py define any function(s).

# functions
def Print_Text():
    print( 'Thank You')

def Add(a,b):
    c=a+b
    return c 

In the other file:

#Import defined functions
from myfun import *

#Call functions
Print_Text()
c=Add(1,2)

Solution2: if this above solution did not work for Colab

  1. Create a foldermyfun
  2. Inside this folder create a file __init__.py
  3. Write all your functions in __init__.py
  4. Import your functions from Colab notebook from myfun import *
ASE
  • 1,702
  • 2
  • 21
  • 29
5

You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Girish M
  • 69
  • 1
  • 3
4

Any of the above solutions didn't work for me. I got ModuleNotFoundError: No module named whtever error. So my solution was importing like below

from . import filename # without .py  

inside my first file I have defined function fun like below

# file name is firstFile.py
def fun():
  print('this is fun')

inside the second file lets say I want to call the function fun

from . import firstFile

def secondFunc():
   firstFile.fun() # calling `fun` from the first file

secondFunc() # calling the function `secondFunc` 
noone
  • 6,168
  • 2
  • 42
  • 51
2

Suppose the file you want to call is anotherfile.py and the method you want to call is method1, then first import the file and then the method

from anotherfile import method1

if method1 is part of a class, let the class be class1, then

from anotherfile import class1

then create an object of class1, suppose the object name is ob1, then

ob1 = class1()
ob1.method1()
Amir Md Amiruzzaman
  • 1,911
  • 25
  • 24
2

in my case i named my file helper.scrap.py and couldn't make it work until i changed to helper.py

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
1

in my main script detectiveROB.py file i need call passGen function which generate password hash and that functions is under modules\passwordGen.py

The quickest and easiest solution for me is

Below is my directory structure

enter image description here

So in detectiveROB.py i have import my function with below syntax

from modules.passwordGen import passGen

enter image description here

Mansur Ul Hasan
  • 2,898
  • 27
  • 24
0

Just a quick suggestion, Those who believe in auto-import by pressing alt+ enter in Pycharm and cannot get help.

Just change the file name from where you want to import by: right-clicking on the file and clicking on refactor-> rename. Your auto-import option will start coming up

Aniket Malik
  • 165
  • 1
  • 10