Get path from open file in Python

后端 未结 4 1272
囚心锁ツ
囚心锁ツ 2020-12-02 17:54

If I have an opened file, is there an os call to get the complete path as a string?

f = open(\'/Users/Desktop/febROSTER2012.xls\')
相关标签:
4条回答
  • 2020-12-02 18:29

    You can get it like this also.

    filepath = os.path.abspath(f.name)
    
    0 讨论(0)
  • 2020-12-02 18:30

    And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

    >>> import os
    >>> f = open('/Users/Desktop/febROSTER2012.xls')
    >>> os.path.dirname(f.name)
    >>> '/Users/Desktop/'
    

    This way you can get hold of the directory structure.

    0 讨论(0)
  • 2020-12-02 18:34

    I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

    >>> import os
    >>> f = open('file.txt')
    >>> os.path.realpath(f.name)
    
    0 讨论(0)
  • 2020-12-02 18:45

    The key here is the name attribute of the f object representing the opened file. You get it like that:

    >>> f = open('/Users/Desktop/febROSTER2012.xls')
    >>> f.name
    '/Users/Desktop/febROSTER2012.xls'
    

    Does it help?

    0 讨论(0)
提交回复
热议问题