如何使用 sys.path.append 在 python 中导入文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32239372/
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
How to import files in python using sys.path.append?
提问by Hunle
There are two directories on my desktop, DIR1
and DIR2
which contain the following files:
有我的桌面上两个目录,DIR1
并且DIR2
包含下列文件:
DIR1:
file1.py
DIR2:
file2.py myfile.txt
The files contain the following:
这些文件包含以下内容:
file1.py
文件1.py
import sys
sys.path.append('.')
sys.path.append('../DIR2')
import file2
file2.py
文件2.py
import sys
sys.path.append( '.' )
sys.path.append( '../DIR2' )
MY_FILE = "myfile.txt"
myfile = open(MY_FILE)
myfile.txt
我的文件.txt
some text
Now, there are two scenarios. The first works, the second gives an error.
现在,有两种情况。第一个有效,第二个给出错误。
Scenario 1
场景一
I cd
into DIR2
and run file2.py
and it runs no problem.
我cd
进入DIR2
并运行file2.py
,它运行没有问题。
Scenario 2
场景二
I cd
into DIR1
and run file1.py
and it throws an error:
我cd
进入DIR1
并运行file1.py
它会引发错误:
Traceback (most recent call last):
File "<absolute-path>/DIR1/file1.py", line 6, in <module>
import file2
File "../DIR2/file2.py", line 9, in <module>
myfile = open(MY_FILE)
IOError: [Errno 2] No such file or directory: 'myfile.txt'
However, this makes no sense to me, since I have appended the path to file1.py
using the command sys.path.append('../DIR2')
.
但是,这对我来说没有意义,因为我已经附加了file1.py
使用命令的路径sys.path.append('../DIR2')
。
Why does this happen when file1.py
, when file2.py
is in the same directory as myfile.txt
yet it throws an error? Thank you.
为什么会在file1.py
, whenfile2.py
位于同一目录中时发生这种情况,myfile.txt
但它会引发错误?谢谢你。
采纳答案by larsks
You can create a path relative to a module by using a module's __file__
attribute. For example:
您可以使用模块的__file__
属性创建相对于模块的路径。例如:
myfile = open(os.path.join(
os.path.dirname(__file__),
MY_FILE))
This should do what you want regardless of where you start your script.
无论您从哪里开始脚本,这都应该做您想做的事情。
回答by demented hedgehog
Replace
代替
MY_FILE = "myfile.txt"
myfile = open(MY_FILE)
with
和
MY_FILE = os.path.join("DIR2", "myfile.txt")
myfile = open(MY_FILE)
That's what the comments your question has are referring to as the relative path solution. This assumes that you're running it from the dir one up from myfile.txt... so not ideal.
这就是您的问题所指的相对路径解决方案的评论。这假设您从 myfile.txt 的目录中运行它......所以不理想。
If you know that my_file.txt is always going to be in the same dir as file2.py then you can try something like this in file2..
如果您知道 my_file.txt 始终与 file2.py 位于同一目录中,那么您可以在 file2..
from os import path
fname = path.abspath(path.join(path.dirname(__file__), "my_file.txt"))
myfile = open(fname)