简体   繁体   English

python,从其他目录下的文件导入当前文件夹下的文件

[英]python, import file under current folder from a file under other directory

I have a package which intends to import a file that user (me) provides 我有一个软件包,打算导入用户(我)提供的文件

In c:\\lib \\calc.py c:\\ lib \\ calc.py

# some codes to find which file to import
filename = "A"
__import__(filename)
...

And I have a file c:\\scripts \\A.py 我有一个文件c:\\ scripts \\ A.py

Note A.py is in a different folder than calc.py. 注意A.py与calc.py位于不同的文件夹中。 Now I'm supposed to do this under command window 现在我应该在命令窗口下执行此操作

cd C:\scripts
python c:\lib\calc.py

but I get an error message 但我收到一条错误消息

No module named A

A.py is in the current folder, why does python fail to find it? A.py在当前文件夹中,为什么python无法找到它? How can I make A.py available? 如何使A.py可用?

Thanks. 谢谢。

You can add the path to your scripts directory in your script calc.py so it can find the A.py module. 您可以在脚本calc.py中将路径添加到脚本目录,以便它可以找到A.py模块。

import sys
sys.path.append('C:\scripts')

If you are on Python version 2.7 or newer you can use the importlib package. 如果您使用的是Python 2.7或更高版本,则可以使用importlib软件包。 The import_module function can accept an absolute path which, IIRC, does not need to be on your PYTHONPATH. import_module函数可以接受绝对路径IIRC,该绝对路径不必位于您的PYTHONPATH上。

import importlib
mod = importlib.import_module(filepath)

Or, if you wanted to manually do the work yourself (or if you are using Python 2.6 or earlier), you can use the imp package directly: 或者,如果您想自己手动进行工作(或者如果您使用的是Python 2.6或更早版本),则可以直接使用imp包:

import imp
mod = imp.load_module(imp.find_module(filename, filepath))

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

相关问题 Django如何从同一文件夹下的另一个文件导入文件? - Django how to import a file from another file under same folder? 如何从其他文件夹 Python 导入文件? - How to import file from other folder Python? Unix下python程序中导入文件 - Import file in python program under Unix 从PYTHONPATH下的嵌套目录访问文件 - Access file from nested directory under PYTHONPATH 如何从 Python 3 中当前目录中的文件导入? - How do I import from a file in the current directory in Python 3? 如何将 python 文件导入另一个 python 文件,其中两个文件都没有类并且位于同一目录下? - How do I import a python file into another python file where both files do not have classes and are under the same directory? 如何使用python从其他调用子目录的目录中导入文件? - How to import file from other directory that call subdirectory by using python? 解析 HTML 文件并存储标题<h1>和副标题</h1><h2>并且文本包含在它们下面的另一个文件目录中(Python)</h2> - Parse HTML file and store the headings <h1> and subheading <h2> and the text contains under them in an other file directory (Python) Python 如何查看子文件夹同级文件夹下是否有文件 - Python how to check if there is file under a folder at the same level of a subfolder python os:获取某个目录下的所有绝对文件路径 - python os: get all absolute file paths under a certain directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM