Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename from file pointer [duplicate]

Tags:

python

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?

like image 382
arjun Avatar asked Mar 05 '13 13:03

arjun


People also ask

How do I get the filename from the file pointer?

use fileno(fp) to get the descriptor. Then, you can use fstat() function. The fstat() function shall obtain information about an open file asso‐ ciated with the file descriptor fildes, and shall write it to the area pointed to by buf. int fstat(int fildes, struct stat *buf);

How do I get the name of a file object in Python?

To get the filename without extension in python, we will import the os module, and then we can use the method os. path. splitext() for getting the name. After writing the above code (Python get filename without extension), Ones you will print “f_name” then the output will appear as a “ file ”.


1 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.

like image 106
mgilson Avatar answered Sep 21 '22 09:09

mgilson