Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name of an open file?

Tags:

python

People also ask

How do I get the filename from a file?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);

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

How do I search for a file in Python?

Python can search for file names in a specified path of the OS. This can be done using the module os with the walk() functions. This will take a specific path as input and generate a 3-tuple involving dirpath, dirnames, and filenames.


One more useful trick to add. I agree with original correct answer, however if you're like me came to this page wanting the filename only without the rest of the path, this works well.

>>> f = open('/tmp/generic.png','r')
>>> f.name
'/tmp/generic.png'
>>> import os
>>> os.path.basename(f.name)
'generic.png'

Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('generic.png','r')
>>> f.name
'generic.png'

Maybe this script is what you want?

import sys, os
print sys.argv[0]
print os.path.basename(sys.argv[0])

When I run the above script I get;

D:\UserData\workspace\temp\Script1.py
Script1.py

Use this code snippet to get the filename you are currently running (i.e .py file):

target_file = inspect.currentframe().f_code.co_filename