从Python子文件夹层次结构中导入内容

6
我正在尝试从test_file层次结构中导入指定的模块。
类似于:
test_case1.py
test_subsuite_2
test_sub_2.1.1.py
test_suite2

能否在这个层次结构上运行导入操作?

/project/main.py
/project/test_files

test_files文件夹的层次结构如下:

test_files
    test_suite1
        test_case1.py
        test_subsuite_1
            test_sub1_1.py
            test_sub1_2.py
        test_subsuite_2
            test_subsuite_2_1
                test_sub_2.1.1.py
            test_sub2_1.py
            test_sub3_2.py

    test_suite2
        test_case2.py
        test_subsuite2_1
            test_sub21_1.py
            test_sub21_2.py
        test_subsuite2_2
            test_sub22_1.py
            test_sub23_2.py
2个回答

5
关键是在包含要导入的文件的所有子文件夹中创建一个空白文件__init__.py。在您的情况下,您将不得不在以下所有文件夹中创建__init__.py文件:
  • test_files
  • test_files\test_suite1
  • test_files\test_suite1\test_subsuite_2
  • test_files\test_suite1\test_subsuite_2\test_subsuite_2_1
此外,在导入文件时,请注意正确指定导入路径,使用从最顶层起的整个路径,并用.分隔不同的文件夹级别。
例如,必须通过指定以下内容来导入test_case1: from test_files.test_suite1 import test_case1 同样地,可以通过指定以下内容来导入test_subsuite_2from test_files.test_suite1 import test_subsuite_2

5
在所有文件夹中创建一个名为__init__.py的空文件。然后,您可以使用.作为文件夹分隔符进行导入。文档在这里。

2
对我来说,这仍然会出现“ImportError:没有名为...的模块”的错误。 - imrek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接