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

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.

查看更多
零度萤火
3楼-- · 2019-01-01 10:35

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

查看更多
裙下三千臣
4楼-- · 2019-01-01 10:36

You can do this in 2 ways. First is just to import the specific function you want from file.py. To do this use

from file import function

Another way is to import the entire file

import file as fl

Then you can call any function inside file.py using

fl.function(a,b)
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 10:40

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

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

查看更多
一个人的天荒地老
6楼-- · 2019-01-01 10:41

There isn't any need to add file.py while importing. Just write from file import function, and then call the function using function(a, b). The reason why this may not work, is because file is one of Python's core modules, so I suggest you change the name of your file.

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.

查看更多
临风纵饮
7楼-- · 2019-01-01 10:41

Came across the same feature but I had to do the below to make it work.

If you are seeing 'ModuleNotFoundError: No module named', you probably need the dot(.) in front of the filename as below;

from .file import funtion

查看更多
登录 后发表回答