How Get Name Of Working File

Maxim Khitrov mkhitrov at gmail.com
Sun Mar 22 11:46:26 EDT 2009


On Sun, Mar 22, 2009 at 10:58 AM, Christian Heimes <lists at cheimes.de> wrote:
> Victor Subervi schrieb:
>> Hi;
>> If I am writing a script that generates HTML, how do I grab the name of the
>> actual file in which I am working? For example, let us say I am working in
>> test.py. I can have the following code:
>>
>> import os
>> dir = os.getcwd()
>>
>> and that will give me the working dir. But what about "test.py"?
>
> The module variable __file__ contains the file name of the current
> Python module.

Keep in mind that __file__ may be set to test.pyc or test.pyo. If you
always want the .py extension, do this:

from os.path import splitext
file = splitext(__file__)[0] + '.py'

- Max



More information about the Python-list mailing list