tags:

views:

65

answers:

2

I am using

file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')

to get a file object specified by the user. Is there any way I can get the absolute path of this file from the File object?

+1  A: 

os.path.abspath should do what you want, if I understand your question correctly.

inkedmn
This works nicely if I pass a string, but I don't know how to get the path as string from my file object :)
ulvund
@ulvund, Try this: file.name works for file objects
Nadia Alramli
Ahh thanks a billion millions Nadia .. that did the trick.
ulvund
**Nadia Alramli** `file.name` is only going to return the path that was originally passed in. If you use `open("test/sample.txt")` and then `os.chdir("/some/other/path")` then `f.name` is still going to return `"test/sample.txt"`
Steve Losh
@Steve, and what is wrong with that? I didn't say file.name will return the full path. I was just answering the OP comment about getting the path as a string from the file object.
Nadia Alramli
+2  A: 
file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')
abs_path = os.path.abspath(file.name)
Dan Lorenc
This will work as long as there's no `os.chdir()` call between those two lines. So in the case of this question it's probably fine, but it's not perfect. I can't think of a way to do it that will always work off the top of my head.
Steve Losh
I don't know of any good reason to use os.chdir() in a GUI app -- at least, not one that also uses threads, and that's the only way you could get a call to chdir() "between" two lines of source that you control.
Peter Hansen