You Are Here Home > __FILE__ equivalent in Python; get the path to current file...

__FILE__ equivalent in Python; get the path to current file in Python

Update:
There is __file__ in Python.

You could do this as suggested by some but I don’t know why:

import inspect
this_file = inspect.currentframe().f_code.co_filename

I hope this helps :)

__FILE__ equivalent in Python; get the path to current file in Python
Filed under: Python   Posted by: Hamid

7 Comments »

  1.  

    It’s __file__ in Python.

    Comment

     
  2. Codehead:
     

    Hey, I know now, it’s very silly but I was searching for it and this was what I found!

    Comment

     
  3. nancy:
     

    The problem with __file__ is that it doesn’t always work. Using the inspect module is more robust.

    Comment

     
  4. Codehead:
     

    Hey, thanks for the info, it would be nice if you could explain this a little more though. Thanks!

    Comment

     
  5.  

    Thanks you man it made my evening. I come from PHP.

    Comment

     
  6. Manu:
     

    cool, thanks for the tip

    Comment

     
  7. juergen:
     

    __file__ doesn’t work in the case when you start the
    python script with execfile(path_to_script).
    Here you get: NameError: name ‘__file__’ is not defined! (Python Version 2.6.2)
    I agree, inspect is more robust.

    Comment

     

RSS feed for comments on this post. TrackBack URL

Leave a comment