116

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?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
arjun
  • 2,333
  • 4
  • 21
  • 21
  • 7
    Note that this isn't exactly a *file pointer*. It's an instance of python's `file` type. – mgilson Mar 05 '13 at 13:59
  • 17
    Pro tip: Use `dir()` on python objects to see what attributes are available. You'd have found `name` easily that way. :-) – Martijn Pieters Mar 05 '13 at 14:01
  • 10
    @MartijnPieters: Or `help(fp)`, which gives you all of the docs for the file type and its methods and data. – Eryk Sun Mar 05 '13 at 14:07
  • 5
    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 Jan 13 '18 at 15:23

1 Answers1

185

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    Correct answer, it was quite useful in getting the file name of uploaded file using Postman for REST API ([Django REST framework](http://www.django-rest-framework.org/)) testing. – hygull Aug 14 '18 at 05:38
  • If the path passed in was a relative path, and the working directory changed `open` call, using `f.name` won't get you the right path, because it will give the path relative to the original working directory. – leewz May 06 '19 at 05:35