Get filename from file pointer

Question:

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?

Asked By: arjun

||

Answers:

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.

Answered By: mgilson
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.