open()找不到相对于PYTHONPATH的给定路径的文件 [英] open() can't find file given path relative to PYTHONPATH

查看:86
本文介绍了open()找不到相对于PYTHONPATH的给定路径的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了export PYTHONPATH=$PYTHONPATH:/home/User/folder/test.然后,当我在/home/User/中运行python并检查sys.path时-正确.

I did export PYTHONPATH=$PYTHONPATH:/home/User/folder/test. Then I ran python when I was in /home/User/ and checked sys.path - it was correct.

>>> import sys
>>> sys.path
['', '/usr/local/lib/python2.7/dist-packages/gitosis-0.2-py2.7.egg', 
'/home/User', '/home/User/folder/test','/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', 
'/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', 
'/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

然后我尝试打开文件/home/User/folder/test/pics/text/text.txt,如下所示:

Then I tried to open a file /home/User/folder/test/pics/text/text.txt like this:

>>>file = open('pics/text/text.txt','r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory:

如您所见,文件路径的前半部分在$PYTHONPATH中,后半部分作为open()函数的参数给出.为什么不起作用?我应该改变什么?

As you can see, first half of path to file is in $PYTHONPATH, and second half is given as an argument to open() function. Why doesn't it work? What should I change?

当我从/home/User/folder/test(导出的路径)运行python并尝试打开文件时-它起作用了.

When I ran python from /home/User/folder/test (exported path) and tried to open file - it worked.

推荐答案

Open是相对于当前目录的,不使用PYTHONPATH.当前目录默认为在命令行上启动python时的目录.

Open is relative to the current directory and does not use PYTHONPATH. The current directory defaults to whatever it was when python was started on the command line.

您可以使用 os更改当前目录. chdir

这篇关于open()找不到相对于PYTHONPATH的给定路径的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆