python如何导入文件夹文件_在Python中从子文件夹导入

1586010002-jmsa.png

This is the situation. I'm using Python 3.6

I currently have the next folder organization:

/MainProject

__init__.py

/Folder1

pyscript1.py

pyscript2.py

__init__.py

/Folder2

pyscript3.py

__init__.py

So, I'm trying to get a function that exists in pyscript1.py from pyscript3. I've also added a init.py at every level. Inside pyscript3.py I tried the following:

from . import Folder1

Giving the error:

ImportError: cannot import name 'Folder1'

Also I tried:

from .Utils import script1

Giving the error:

ModuleNotFoundError: No module named '__main__.Utils'; '__main__' is not a

package

I know that I can solve it using sys and os in the following manner:

sys.path.append(os.path.realpath('../..'))

But I wanted to know if this is possible without using sys.

解决方案

Note that Folder1 is a directory, the .py scripts are your modules.

In pyscript3 you should be able to go:

from Folder1 import pyscript1

Then you can access a method with name methodname like:

pyscript1.methodname()

Otherwise you can import the method directly like:

from Folder1.pyscript1 import methodname

and use it like:

methodname()

EDIT:

For your program to see Folder1 and Folder2, you need to run your program from the MainProject folder.

Either move pyscript3 to your MainFolder or write another script, let's call it main.py, and call the necessary code to instantiate the class/call the function you want in pyscript3.py.

To summarize, you always want to run the entry module from the base folder of your project.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值