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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With