从同级文件夹导入文件

时间:2020-09-18 04:57:02

标签: python import

我正尝试从同级文件夹中导入功能,我可以,我正在寻找文档,但没有找到有用的东西,请您帮我吗?

我有一个名为fold1的文件夹,里面有fold2和fold3,在fold2里有filetoimport.py,它有:

def fntest(a, b):
    return print(a+b)

我想从fold3文件main.py内部导入该功能,

from fold2 import filetoimport

filetoimport.fntest(2,2)

然后我得到一个错误:

Traceback (most recent call last):
File "fold3/main.py", line 1, in <module>
fold1 import filetoimport
ImportError: No module named 'fold1'

希望你能帮助我:)

我也尝试过

from fold1.fold2 import filetoimport

但是失败了。

3 个答案:

答案 0 :(得分:0)

您需要导入父文件夹作为程序可以在其中检查更多模块的路径。我为此感到幸运

http://localhost:8080/oslc/cqrest
# as in
http://localhost:8080/oslc/cqrest/repo/7.0.0/db/SAMPL/record/?oslc_cm.query=Found_in_Product_Family="MyDefectFamily"&rcm.type=Defect

答案 1 :(得分:0)

好的,这应该有效

import sys
import os
sys.path.insert(1,os.popen('pwd').read().replace('3\n','2'))

import filetoimport

filetoimport.fntest(2,2)

您只需要将目标文件夹添加到python运行时路径

答案 2 :(得分:0)

据我了解,您的文件夹结构如下

fold1
    fold2
        -- filetoimport.py
    fold3 
        -- main.py

   

您似乎正在从终端执行 main.py 文件(通过打开 fold1 路径)为

python3 fold3/main.py

enter image description here

相反,您应该将命令执行为

python3 -m fold3.main

enter image description here

由于自变量是模块名称,因此不能指定文件扩展名(.py)

另一方面,如果您在pycharm或intellij idea之类的IDE中以项目形式打开 fold1 并通过IDE本身执行 main.py ,则不会出错

希望,这将解决您的问题。