Get path from open file in Python

Python

Python Problem Overview


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

From f, how would I get "/Users/Desktop/febROSTER2012.xls" ?

Python Solutions


Solution 1 - Python

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?

Solution 2 - Python

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)

Solution 3 - Python

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.

Solution 4 - Python

You can get it like this also.

filepath = os.path.abspath(f.name)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid542View Question on Stackoverflow
Solution 1 - PythonTadeckView Answer on Stackoverflow
Solution 2 - PythonZansView Answer on Stackoverflow
Solution 3 - PythonAli Raza BhayaniView Answer on Stackoverflow
Solution 4 - PythonanswerSeekerView Answer on Stackoverflow