导入的代码无法打开其目录中的文件

Pha*_*ani 0 python import

我有以下文件结构:

test/
    test1.py
test2.py
text.txt
Run Code Online (Sandbox Code Playgroud)

以下是文件的内容

test1.py:

import sys
sys.path.append('../')
import test2

test2.read()
Run Code Online (Sandbox Code Playgroud)

test2.py:

def read():
    with open('text.txt', 'rb') as f:
        print f.read()

if __name__ == "__main__":
    read()
Run Code Online (Sandbox Code Playgroud)

text.txt包含一行文字.当我运行时test1.py,我收到"找不到文件"错误:

Traceback (most recent call last):
  File "test1.py", line 5, in <module>
    test2.read()
  File "../test2.py", line 2, in read
    with open('text.txt', 'rb') as f:
IOError: [Errno 2] No such file or directory: 'text.txt'
Run Code Online (Sandbox Code Playgroud)

我有点理解为什么会出现这个错误.但是我该如何处理这些错误呢.我希望代码test2.py就像我可以在任何地方使用的库代码.

Eli*_*sha 5

sys.path用于python路径(PYTHONPATHeviroment变量).即当你在import某些库时,在哪里寻找python 库.它不会影响在哪里open()寻找文件.

当你open(filename).在filename相对于procees 工作目录.(代码运行的路径)

因此,如果要访问其路径相对于代码文件路径的flie,则可以使用__file__包含当前文件路径的builtin变量.

所以你可以改为test2.py:

import os

def read():
    with open(os.path.join(os.path.dirname(__file__),'text.txt'), 'rb') as f:
        print f.read()
Run Code Online (Sandbox Code Playgroud)

  • 此外,我认为提及["当前工作目录"](http://en.wikipedia.org/wiki/Working_directory)的概念与维基百科链接或一些更好的链接可能会使这比仅仅"运行代码的地方"更清楚从".因为正如所写的那样,它意味着`test1.py`所在的目录才是最重要的,而事实并非如此. (2认同)
  • @Phani:即使是正在进行的研究工作,将其制作成可安装的软件包也可以让您轻松完成各种任务.这意味着你可以使用`setuptools`.这意味着您可以拥有28个分叉或分支版本的源,它们共享相同的数据文件.您可以轻松添加Cython或C扩展,而不使用`setup.py`手动执行它是一场噩梦.您可以记录和自动化您的依赖项,因此迁移到新计算机或升级到新的Python很容易.等等. (2认同)