Python – How to get the name of an open file

python

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?

Best Answer

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'