如何导入位于当前工作目录中的 Python 库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16021013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:37:21  来源:igfitidea点击:

How can I import a Python library located in the current working directory?

pythonpython-3.x

提问by Nathan2055

I'm writing an installation program that will pull a script out of an existing Python file and then use it in the main Python program. What I need to know how to do is import <file>from the current working directory, not the standard library or the directory the main code is in. How can I do that?

我正在编写一个安装程序,它将从现有的 Python 文件中提取一个脚本,然后在主 Python 程序中使用它。我需要知道如何做的是import <file>从当前工作目录,而不是标准库或主代码所在的目录。我该怎么做?

回答by Tyler Eaves

Something like this should work (untested)

像这样的东西应该可以工作(未经测试)

import os
import sys
sys.path.append(os.getcwd())
import foo

回答by woemler

import sys
sys.path.append('path/to/your/file')
import your.lib

This will import the contents of your file from the newly appended directory. Appending new directories to the Python Path in this way only lasts while the script is running, it is not permanent.

这将从新附加的目录中导入文件的内容。以这种方式将新目录附加到 Python 路径只在脚本运行时持续,它不是永久性的。

回答by piokuc

You should be able to import the module from your current working directory straight away. If not, you can add your current working directory to sys.path:

您应该能够立即从当前工作目录导入模块。如果没有,您可以将当前工作目录添加到sys.path

import sys
sys.path.insert(0, 'path_to_your_module') # or: sys.path.insert(0, os.getcwd())
import your_module

You can also add the directory to PYTHONPATH environment variable.

您还可以将目录添加到 PYTHONPATH 环境变量中。