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

后端 未结 3 834
暖寄归人
暖寄归人 2021-01-16 07:38

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

相关标签:
3条回答
  • 2021-01-16 08:02

    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

    0 讨论(0)
  • 2021-01-16 08:04

    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

    0 讨论(0)
  • 2021-01-16 08:10

    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
    
    0 讨论(0)
提交回复
热议问题