Get path from open file in Python
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization
--
Chapters
00:00 Get Path From Open File In Python
00:20 Accepted Answer Score 195
00:36 Answer 2 Score 157
00:56 Answer 3 Score 17
01:16 Answer 4 Score 8
01:23 Thank you
--
Full question
https://stackoverflow.com/questions/9542...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Civilization
--
Chapters
00:00 Get Path From Open File In Python
00:20 Accepted Answer Score 195
00:36 Answer 2 Score 157
00:56 Answer 3 Score 17
01:16 Answer 4 Score 8
01:23 Thank you
--
Full question
https://stackoverflow.com/questions/9542...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 198
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?
ANSWER 2
Score 158
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)
ANSWER 3
Score 17
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.
ANSWER 4
Score 8
You can get it like this also.
filepath = os.path.abspath(f.name)