473,287 Members | 1,565 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

__file__ vs __FILE__

I apologize in advance for coming at this from this angle but...

In PHP you have the __FILE__ constant which gives you the value of the
absolute path of the file you're in (as opposed to the main script
file.) With the function dirname, this makes it easy to get the
parent dir of a particular file from within that file:

$parent_dir = dirname(__FILE__);

I'm looking for the best way to accomplish this in Python. This seems
to work:

parent_dir = os.path.normpath(os.path.join(os.path.abspath(__fi le__),
'..'))

Can anyone confirm the reliability of this method or suggest a better
(one-line) method for accomplishing this?

Thanks,
Tom

Nov 3 '07 #1
10 12352
The __file__ attribute is present when you run a script from a file.
If you run from the interactive interpreter, it will raise a
NameError. Likewise, I believe that in earlier versions of Python
(2.1? Pre 2.2?) it was only set within imported modules. I've used the
'os.path.realpath(os.path.pardir)' construct in a couple of scripts
myself. That ought to work within the interactive interpreter.

Jeff

On Nov 2, 2007, at 11:21 PM, klenwell wrote:
I apologize in advance for coming at this from this angle but...

In PHP you have the __FILE__ constant which gives you the value of the
absolute path of the file you're in (as opposed to the main script
file.) With the function dirname, this makes it easy to get the
parent dir of a particular file from within that file:

$parent_dir = dirname(__FILE__);

I'm looking for the best way to accomplish this in Python. This seems
to work:

parent_dir = os.path.normpath(os.path.join(os.path.abspath(__fi le__),
'..'))

Can anyone confirm the reliability of this method or suggest a better
(one-line) method for accomplishing this?

Thanks,
Tom

--
http://mail.python.org/mailman/listinfo/python-list
Nov 3 '07 #2
Jeff McNeil wrote:
I've used the 'os.path.realpath(os.path.pardir)' construct in a
couple of scripts myself.
In Windows? Using Linux, this gives me "..".

I use os.path.dirname(os.path.abspath(__file__))
That ought to work within the interactive interpreter.
Why do you also enter that code in the interpreter? If it is in a
module, you should always be able to use __file__.

Regards,
Björn

--
BOFH excuse #238:

You did wha... oh _dear_....

Nov 3 '07 #3
On 3 Nov, 04:21, klenwell <klenw...@gmail.comwrote:
I apologize in advance for coming at this from this angle but...

In PHP you have the __FILE__ constant which gives you the value of the
absolute path of the file you're in (as opposed to the main script
file.) With the function dirname, this makes it easy to get the
parent dir of a particular file from within that file:

$parent_dir = dirname(__FILE__);

I'm looking for the best way to accomplish this in Python. This seems
to work:

parent_dir = os.path.normpath(os.path.join(os.path.abspath(__fi le__),
'..'))

Can anyone confirm the reliability of this method or suggest a better
(one-line) method for accomplishing this?

Thanks,
Tom
This is not really 'one-line' since you have to import two modules
first, but it looks nicer...:

import sys, os
print sys.argv[0] # absolute file name
print os.path.dirname(sys.argv[0]) # absolute dir name

Nov 3 '07 #4
En Sat, 03 Nov 2007 10:07:10 -0300, Giampaolo Rodola' <gn****@gmail.com>
escribió:
On 3 Nov, 04:21, klenwell <klenw...@gmail.comwrote:
>In PHP you have the __FILE__ constant which gives you the value of the
absolute path of the file you're in (as opposed to the main script
file.)
This is not really 'one-line' since you have to import two modules
first, but it looks nicer...:

import sys, os
print sys.argv[0] # absolute file name
print os.path.dirname(sys.argv[0]) # absolute dir name
Note that this returns the location of the *main* script, not the current
module, as the OP explicitely asked for.

--
Gabriel Genellina

Nov 3 '07 #5
I'm using Mac OS X, and it get:

Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>import os
os.getcwd()
'/Users/jeff'
>>os.path.realpath(os.path.pardir)
'/Users'
>>>
The __file__ construct is fine from within a module and is probably
more inline with what the OP was looking for anyways.

On Nov 3, 2007, at 7:18 AM, Bjoern Schliessmann wrote:
Jeff McNeil wrote:
>I've used the 'os.path.realpath(os.path.pardir)' construct in a
couple of scripts myself.

In Windows? Using Linux, this gives me "..".

I use os.path.dirname(os.path.abspath(__file__))
>That ought to work within the interactive interpreter.

Why do you also enter that code in the interpreter? If it is in a
module, you should always be able to use __file__.

Regards,
Björn

--
BOFH excuse #238:

You did wha... oh _dear_....

--
http://mail.python.org/mailman/listinfo/python-list
Nov 3 '07 #6
On Nov 3, 4:18 am, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n...@spamgourmet.comwrote:
Jeff McNeil wrote:
I've used the 'os.path.realpath(os.path.pardir)' construct in a
couple of scripts myself.

In Windows? Using Linux, this gives me "..".

I use os.path.dirname(os.path.abspath(__file__))
That ought to work within the interactive interpreter.

Why do you also enter that code in the interpreter? If it is in a
module, you should always be able to use __file__.

Regards,

Björn

--
BOFH excuse #238:

You did wha... oh _dear_....
I use os.path.dirname(os.path.abspath(__file__))
That makes sense, as it is almost a literal translation of what I'm
used to using in PHP. Thanks for pointing this out.

Nov 3 '07 #7
klenwell wrote:
Bjoern Schliessmann wrote:
>I use os.path.dirname(os.path.abspath(__file__))

That makes sense, as it is almost a literal translation of what
I'm used to using in PHP. Thanks for pointing this out.
You're welcome, happy coding :)

Regards,
Björn

--
BOFH excuse #286:

Telecommunications is downgrading.

Nov 4 '07 #8
On 3 Nov, 15:46, "Gabriel Genellina" <gagsl-...@yahoo.com.arwrote:
En Sat, 03 Nov 2007 10:07:10 -0300, Giampaolo Rodola' <gne...@gmail.com
escribió:
On 3 Nov, 04:21, klenwell <klenw...@gmail.comwrote:
In PHP you have the __FILE__ constant which gives you the value of the
absolute path of the file you're in (as opposed to the main script
file.)
This is not really 'one-line' since you have to import two modules
first, but it looks nicer...:
import sys, os
print sys.argv[0] # absolute file name
print os.path.dirname(sys.argv[0]) # absolute dir name

Note that this returns the location of the *main* script, not the current
module, as the OP explicitely asked for.

--
Gabriel Genellina
Whoops! You're right.

Nov 5 '07 #9
interestingly...
I wanted to reuse this code so i wrote function in a file

def getParentDir():
import os
return os.path.dirname(os.path.abspath(__file__))
and called this function, in another file, its giving me parent
directory of file where this function is defined.?
how to reuse this piece of code then? or am i doing something wrong?

btw using __path__[0], I can get the parent directory of file too...
sandip


On Nov 5, 5:09 am, Giampaolo Rodola' <gne...@gmail.comwrote:
On 3 Nov, 15:46, "Gabriel Genellina" <gagsl-...@yahoo.com.arwrote:
En Sat, 03 Nov 2007 10:07:10 -0300, Giampaolo Rodola' <gne...@gmail.com
escribió:
On 3 Nov, 04:21, klenwell <klenw...@gmail.comwrote:
>In PHP you have the __FILE__ constant which gives you the value of the
>absolute path of the file you're in (as opposed to the main script
>file.)
This is not really 'one-line' since you have to import two modules
first, but it looks nicer...:
import sys, os
print sys.argv[0] # absolute file name
print os.path.dirname(sys.argv[0]) # absolute dir name
Note that this returns the location of the *main* script, not the current
module, as the OP explicitely asked for.
--
Gabriel Genellina

Whoops! You're right.

Nov 5 '07 #10
On Nov 5, 1:07 am, sandipm <sandip.m...@gmail.comwrote:
interestingly...
I wanted to reuse this code so i wrote function in a file

def getParentDir():
import os
return os.path.dirname(os.path.abspath(__file__))

and called this function, in another file, its giving me parent
directory of file where this function is defined.?
This is true. __file__ is defined at the module level where the
function is defined.
how to reuse this piece of code then? or am i doing something wrong?
You have a few choices. You could implement it wherever you need it
which might actually be nice from a OO point of view. You could modify
the function above to accept a parameter and operate on the __file__
attribute of that parameter. Or, you could use the inspect module to
look at the stack and operate on the __file__ attribute of the caller.

The first one is obvious to implement, although it will only apply to
modules you have implemented. The second one I think someone has
already posted a solution to. Here is how to implement the third one
(this is also usable with a parameter).

Expand|Select|Wrap|Line Numbers
  1. import inspect
  2. import os
  3.  
  4. def getpardir(obj=None):
  5. if obj is None:
  6. obj = inspect.stack()[1][0]
  7. return os.path.dirname(inspect.getfile(obj))
  8.  
Some may choose to stay away from this sort of thing though, since
inspecting the stack can tend to feel a bit like voo-doo. Passing a
parameter is probably your best bet IMHO.

Matt

Nov 5 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Chris Pomasl | last post by:
We picked up a helpdesk script from sourceforge, Mantis. This script uses the __FILE__ magic constant to ostensibly derive the path to the include directory from a script in the top level...
1
by: Chris Pomasl | last post by:
Does no one have any insight?......please? Chris -------- Original Message -------- Subject: Problem with __FILE__ magic constant Date: Tue, 06 Jan 2004 16:43:41 GMT From: Chris Pomasl...
6
by: Tom | last post by:
I'm trying to dynamically adjust the path for one of my scripts using this: $script_path = str_replace( $_SERVER, "", dirname(realpath(__FILE__)) ) . DIRECTORY_SEPARATOR; The problem: the...
1
by: Spry | last post by:
Hi, I wanted to write macros for finding the number of memory allocations and deallocations also wanted to find the locations. The code I have is a pretty big one. I have a wrapper on top of...
5
by: jake1138 | last post by:
I couldn't find an example of this anywhere so I post it in the hope that someone finds it useful. I believe this is compiler specific (I'm using gcc), as C99 defines __VA_ARGS__. Comments are...
5
by: baumann.Pan | last post by:
where are these macros defined? can I use it a release ver code?
2
by: fortepianissimo | last post by:
This is a question to all of you who use Komodo IDE for development: when I tried to debug my script which uses __file__ to get the absolute path to the file, Komodo complained that the variable is...
18
by: Lukas Ruf | last post by:
Dear all, for debugging purposes, I like the pre-compiler macros __FILE__, __FUNCTION__, __LINE__ I have been wondering if there is a short form of __FILE__ that provides only the filename...
3
by: mh | last post by:
So on most modules I import, I can access the .__file__ attribute to find the implementation. ie: >>> import time >>> time.__file__ '/data1/virtualpython/lib/python2.3/lib-dynload/timemodule.so'...
4
by: 7stud | last post by:
Hi, I'm having trouble understanding what the definition of __file__ is. With this program: ------ #data.py: def show(): print __file__
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.