How to get the name of an open file?

Viewed 88456

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?

4 Answers
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
Related