简体   繁体   English

如何使用sys.path.append在python中导入文件?

[英]How to import files in python using sys.path.append?

There are two directories on my desktop, DIR1 and DIR2 which contain the following files: 我的桌面上有两个目录, DIR1DIR2 ,它们包含以下文件:

DIR1:
file1.py

DIR2:
file2.py  myfile.txt

The files contain the following: 这些文件包含以下内容:

file1.py file1.py

import sys

sys.path.append('.')
sys.path.append('../DIR2')

import file2

file2.py file2.py

import sys

sys.path.append( '.' )
sys.path.append( '../DIR2' )

MY_FILE = "myfile.txt"

myfile = open(MY_FILE) 

myfile.txt myfile.txt文件

some text

Now, there are two scenarios. 现在,有两种情况。 The first works, the second gives an error. 第一个工作,第二个给出错误。

Scenario 1 场景1

I cd into DIR2 and run file2.py and it runs no problem. cdDIR2和运行file2.py它运行没有问题。

Scenario 2 情景2

I cd into DIR1 and run file1.py and it throws an error: cdDIR1和运行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') . 但是,这对我来说没有任何意义,因为我使用命令sys.path.append('../DIR2')将路径附加到file1.py

Why does this happen when file1.py , when file2.py is in the same directory as myfile.txt yet it throws an error? 为什么在file1.py时会发生这种情况,当file2.pymyfile.txt在同一目录中file2.py会抛出错误? Thank you. 谢谢。

You can create a path relative to a module by using a module's __file__ attribute. 您可以使用模块的__file__属性创建相对于模块的路径。 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. 无论您在何处启动脚本,都应该按照自己的意愿行事。

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)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM