open() can't find file given path relative to PYTHONPATH

我的未来我决定 提交于 2019-12-20 06:26:53

问题


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']

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:

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?

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


回答1:


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.

You can change the current directory with os.chdir




回答2:


If I'm reading your question correctly, you want your data to reside in a location relative to the module. If that's the case, you can use:

full_path = os.path.join(os.path.split(__file__)[:-1]+['pics','text','text.txt'])

__file__ is the path to the module (including modulename.py). So I split that path, pull off modulename.py ([:-1]) and add the rest of the relative path via os.path.join




回答3:


Whenever I want to import a script, relative to current and don't use packages, I usually use

sys.path = [os.path.dirname(__file__) + "/../another_dir"] + sys.path


来源:https://stackoverflow.com/questions/12391709/open-cant-find-file-given-path-relative-to-pythonpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!