从不同文件夹导入文件 [英] Importing files from different folder

查看:40
本文介绍了从不同文件夹导入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件夹结构.

application
├── app
│   └── folder
│       └── file.py
└── app2
    └── some_folder
        └── some_file.py

我想从 some_file.py 中的 file.py 导入一些函数.

I want to import some functions from file.py in some_file.py.

我试过了

from application.app.folder.file import func_name

以及其他一些尝试,但到目前为止我无法正确导入.我该怎么做?

and some other various attempts but so far I couldn't manage to import properly. How can I do this?

推荐答案

注意:这个答案是针对一个非常具体的问题.对于大多数从搜索引擎来到这里的程序员来说,这不是您要寻找的答案.通常,您会将文件组织成包(参见其他答案),而不是修改搜索路径.

Note: This answer was intended for a very specific question. For most programmers coming here from a search engine, this is not the answer you are looking for. Typically you would structure your files into packages (see other answers) instead of modifying the search path.

默认情况下,您不能.导入文件时,Python 仅搜索运行入口点脚本的目录和 sys.path,其中包括包安装目录(实际上是 比这更复杂一些,但这涵盖了大多数情况.

By default, you can't. When importing a file, Python only searches the directory that the entry-point script is running from and sys.path which includes locations such as the package installation directory (it's actually a little more complex than this, but this covers most cases).

但是,您可以在运行时添加到 Python 路径:

However, you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

这篇关于从不同文件夹导入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆