How to get the name of an open file?

Each Answer to this Q is separated by one/two green lines.

I’m trying to store in a variable the name of the current file that I’ve opened from a folder.

How can I do that?
I’ve tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file.

Can you please help me?

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .