简体   繁体   English

如何在两个子目录中导入python文件

[英]How to import python files within two subdirectories

I have a directory structure as below 我有一个目录结构如下

 - src\module1\ __init__.py 
 - src\module1\foo1.py 
 - src\module2\ __init__.py
 - src\module2\foo2.py

I want to import functions from foo1.py in foo2.py. 我想从foo2.py中的foo1.py导入函数。 I tried importing using 我尝试使用导入

from module1.foo1 import *

but this is throwing traceback error. 但这会引发回溯错误。 please suggest how to import foo1.py in foo2.py 请建议如何导入foo1.pyfoo2.py

Thanks in advance manu 在此先感谢manu

尝试这个

from module1.foo1 import ClassName

From https://docs.python.org/2/tutorial/modules.html https://docs.python.org/2/tutorial/modules.html

6.1.2. 6.1.2。 The Module Search Path 模块搜索路径

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. 如果找不到,它将在变量sys.path给出的目录列表中搜索名为spam.py的文件。 sys.path is initialized from these locations: sys.path从以下位置初始化:

the directory containing the input script (or the current directory). 包含输入脚本的目录(或当前目录)。

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). PYTHONPATH(目录名称列表,语法与shell变量PATH相同)。

the installation-dependent default. 取决于安装的默认值。

After initialization, Python programs can modify sys.path. 初始化后,Python程序可以修改sys.path。

So let's modify sys.path 因此,让我们修改sys.path

import sys
sys.path.append('src\module1\')
import foo1

It's worth printing sys.path so you can see why it's not being found already. 值得打印sys.path,因此您可以查看为什么尚未找到它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历目录中的子目录并计算python中子目录中的文件 - How to iterate through subdirectories in a directory and count the files in the subdirectories in python 如何在多个子目录中找到具有相同扩展名的所有文件并使用 python 将它们移动到单独的文件夹中? - How can find all files of the same extension within multiple subdirectories and move them to a seperate folder using python? 如何加入子目录和文件的名称进行处理-Python - How to join names of subdirectories and files for processing - python 在python中具有多个子目录的运行时导入 - Runtime import with with multiple subdirectories in python 如何在 Python 中将两个 python 文件作为单个模块导入? - How to import two python files as a single module in Python? 在python中,如何获取目录中所有文件的路径,包括子目录中的文件,但不包括子目录的路径 - In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories 在Python中,如何查找目录下的所有文件,包括子目录中的文件? - In Python, how to find all the files under a directory, including the files in subdirectories? 如何从python中的两个文件夹导入Excel文件 - how to import excel files from two folders in python 如何将文件导入python - how to import files into python 仅使用python查找子目录中的文件 - find files in subdirectories only with python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM