我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
我有这样的文件夹结构:
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
如何从file.py或some_file.py中导入函数?我尝试了:
from application.app.folder.file import func_name
但它不起作用。
当前回答
将application作为python项目的根目录,在application、app和文件夹文件夹中创建一个空__init__.py文件。然后在some_file.py中进行如下更改以获得func_name的定义:
import sys
sys.path.insert(0, r'/from/root/directory/application')
from application.app.folder.file import func_name ## You can also use '*' wildcard to import all the functions in file.py file.
func_name()
其他回答
我多次遇到同一个问题,所以我想分享我的解决方案。
Python版本:3.X
以下解决方案适用于在Python 3.X版本中开发应用程序的人,因为自2020年1月1日以来,Python 2不受支持。
项目结构
在python3中,由于隐式命名空间包,项目子目录中不需要__init__.py。请参见Python 3.3中的包是否不需要init.py+
Project
├── main.py
├── .gitignore
|
├── a
| └── file_a.py
|
└── b
└── file_b.py
问题陈述
在file_b.py中,我想在文件夹a下的file_a.py中导入一个类a。
解决
#1快速但肮脏的方式
不安装软件包,就像您当前正在开发一个新项目
使用try-catch检查是否存在错误。代码示例:
import sys
try:
# The insertion index should be 1 because index 0 is this file
sys.path.insert(1, '/absolute/path/to/folder/a') # the type of path is string
# because the system path already have the absolute path to folder a
# so it can recognize file_a.py while searching
from file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
#2安装软件包
安装应用程序后(在本文中,不包括安装教程)
你可以简单地
try:
from __future__ import absolute_import
# now it can reach class A of file_a.py in folder a
# by relative import
from ..a.file_a import A
except (ModuleNotFoundError, ImportError) as e:
print("{} fileure".format(type(e)))
else:
print("Import succeeded")
编码愉快!
在linux上的python3中为我工作
import sys
sys.path.append(pathToFolderContainingScripts)
from scriptName import functionName #scriptName without .py extension
只需使用os模块中的change-dir函数:
os.chdir("Here new director")
比正常情况下可以导入的更多信息
据我所知,直接在要导入的函数的文件夹中添加__init__.py文件即可完成此任务。
哇,我没想到会花这么多时间在这上面。以下内容对我有用:
操作系统:Windows 10
Python:v3.10.0
注意:由于我是Python v3.10.0,所以我没有使用__init__.py文件,这对我来说无论如何都不起作用。
application
├── app
│ └── folder
│ └── file.py
└── app2
└── some_folder
└── some_file.py
王旭的第一个解决方案对我有效。为了清楚起见,我将其转发了一个绝对的文件参考:
import sys
sys.path.insert(1, 'C:\\Users\\<Your Username>\\application')
import app2.some_folder.some_file
some_file.hello_world()
替代解决方案:然而,这也对我有效:
import sys
sys.path.append( '.' )
import app2.some_folder.some_file
some_file.hello_world()
虽然,我不明白为什么它会起作用。我以为点是对当前目录的引用。但是,当打印出当前文件夹的路径时,当前目录已列在顶部:
for path in sys.path:
print(path)
希望有人能在评论中澄清为什么这样做有效。尽管如此,我也希望它能帮助一些人。