如何使用sys.path.append在python中导入文件? [英] How to import files in python using sys.path.append?
问题描述
我的桌面上有两个目录,DIR1
和DIR2
,其中包含以下文件:
There are two directories on my desktop, DIR1
and DIR2
which contain the following files:
DIR1:
file1.py
DIR2:
file2.py myfile.txt
文件包含以下内容:
import sys
sys.path.append('.')
sys.path.append('../DIR2')
import file2
file2.py
import sys
sys.path.append( '.' )
sys.path.append( '../DIR2' )
MY_FILE = "myfile.txt"
myfile = open(MY_FILE)
myfile.txt
some text
现在,有两种情况.第一个起作用,第二个给出错误.
Now, there are two scenarios. The first works, the second gives an error.
我cd
进入DIR2
并运行file2.py
,它没有问题.
I cd
into DIR2
and run file2.py
and it runs no problem.
我cd
进入DIR1
并运行file1.py
并抛出错误:
I cd
into DIR1
and run file1.py
and it throws an error:
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'
但是,这对我来说毫无意义,因为我已经使用命令sys.path.append('../DIR2')
将路径附加到了file1.py
.
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
和file2.py
与myfile.txt
在同一目录中时却发生错误,为什么会发生这种情况?谢谢你.
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.
推荐答案
您可以使用模块的__file__
属性来创建相对于模块的路径.例如:
You can create a path relative to a module by using a module's __file__
attribute. For example:
myfile = open(os.path.join(
os.path.dirname(__file__),
MY_FILE))
无论您从哪里开始脚本,这都应该做您想要的事情.
This should do what you want regardless of where you start your script.
这篇关于如何使用sys.path.append在python中导入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!