42

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
  • you should be clear, do you mean the .py file (i.e. the script itself) or a file you opened using open("filename")?? – hasen Nov 28 '08 at 20:16

4 Answers4

77

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'
James Errico
  • 5,876
  • 1
  • 20
  • 16
47
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'
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
  • beware that `f.name` does not change when renaming the file, while the file handler will still point to the file now located under a different name. (at least in my distribution of gnu/linux this is the case). So, strictly speaking, `f.name` does not necessarily return the current file name – Bastian Mar 20 '21 at 21:47
  • 1
    That's true. But that's true in any language as the data structure is populated when making the call to open(). The only way around that behavior is to subscribe to the file rename event via inotify in linux or equivalent in other OSs. See https://stackoverflow.com/questions/44651492/can-i-monitor-the-file-re-name-event-on-linux – Vinko Vrsalovic Mar 22 '21 at 13:42
7

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
Rudiger Wolf
  • 1,760
  • 12
  • 15
0

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

target_file = inspect.currentframe().f_code.co_filename
kishkin
  • 5,152
  • 1
  • 26
  • 40