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
?
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);
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 ”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With