Call a function from another file in Python

2019-01-01 10:12发布

Set_up: I have a .py file for each function I need to use in a program.

In this program, I need to call the function from the external files.

I've tried:

from file.py import function(a,b)

But I get the error:

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

How do I fix this problem?

12条回答
梦该遗忘
2楼-- · 2019-01-01 10:19

First of all you do not need a .py.

If you have a file a.py and inside you have some functions:

def b():
  # Something
  return 1

def c():
  # Something
  return 2

And you want to import them in z.py you have to write

from a import b, c
查看更多
残风、尘缘若梦
3楼-- · 2019-01-01 10:19

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
查看更多
像晚风撩人
4楼-- · 2019-01-01 10:19

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

查看更多
长期被迫恋爱
5楼-- · 2019-01-01 10:19

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()
查看更多
谁念西风独自凉
6楼-- · 2019-01-01 10:22

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()
查看更多
残风、尘缘若梦
7楼-- · 2019-01-01 10:35

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
查看更多
登录 后发表回答