Get path from open file in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Question
00:27 Accepted answer (Score 193)
00:48 Answer 2 (Score 148)
01:08 Answer 3 (Score 17)
01:32 Answer 4 (Score 8)
01:44 Thank you
--
Full question
https://stackoverflow.com/questions/9542...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Jungle Looping
--
Chapters
00:00 Question
00:27 Accepted answer (Score 193)
00:48 Answer 2 (Score 148)
01:08 Answer 3 (Score 17)
01:32 Answer 4 (Score 8)
01:44 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)