103
votes

If I have a file pointer is it possible to get the filename?

fp = open("C:\hello.txt")

Is it possible to get "hello.txt" using fp?

1
Note that this isn't exactly a file pointer. It's an instance of python's file type. - mgilson
Pro tip: Use dir() on python objects to see what attributes are available. You'd have found name easily that way. :-) - Martijn Pieters♦
@MartijnPieters: Or help(fp), which gives you all of the docs for the file type and its methods and data. - Eryk Sun
I've voted to reopen. IMO the distinction between getting the file path and the file name is enough to justify letting this question stand on its own right; many Googlers landing here will benefit from the mention of os.path.basename in the answer which would be irrelevant on the other question. - Mark Amery

1 Answers

151
votes

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.