finding out absolute path to a file from python

后端 未结 5 443
孤城傲影
孤城傲影 2020-12-11 14:49

If I have a file test.py that resides in some directory, how can I find out from test.py what directory it is in? os.path.curdir will

相关标签:
5条回答
  • 2020-12-11 15:25

    os.path has lots of tools for dealing with paths and getting information about paths.

    Particularly, you want:

    os.path.abspath
    
    0 讨论(0)
  • 2020-12-11 15:35

    the answer is to use:

     __file__
    

    which returns a relative path.

    os.path.abspath(__file__) 
    

    can be used to get the full path.

    0 讨论(0)
  • 2020-12-11 15:46
    import os
    dirname, filename = os.path.split(os.path.abspath(__file__))
    
    0 讨论(0)
  • 2020-12-11 15:50

    The answers so far have correctly pointed you to os.path.abspath, which does exactly the job you requested. However don't forget that os.path.normpath and os.path.realpath can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these "many" is impossible to tell from the scant info we have, of course;-).

    0 讨论(0)
  • 2020-12-11 15:51

    Here's how to get the directory of the current file:

    import os
    os.path.abspath(os.path.dirname(__file__))
    
    0 讨论(0)
提交回复
热议问题