Get filename from file pointer

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionarjunView Question on Stackoverflow
Solution 1 - PythonmgilsonView Answer on Stackoverflow