Find directory name of file?

Peter Hansen peter at engcorp.com
Mon Jan 30 22:37:29 CET 2006


Blair P. Houghton wrote:
> Wanna see something freaky?
> 
> In IDLE, I type the following:
> 
>     >>> import sys
>     >>> import os.path
>     >>> os.path.abspath(sys.argv[0])
>     'C:\\Program Files\\Python\\2.4'
> 
> Pretty normal, right?  

Depends on your definition of normal.  That doesn't look to me like it's 
the path to IDLE.  Anyway, sys.argv[0] is probably documented as being 
undefined when you run an interactive session...

 > Then I type this:
> 
>     >>> print sys.argv[0]
> 
>     >>>
> 
> Yup.  No output.  Even if I wrap the sys.argv[0] in something visible,

The correct way to see what's really in a string is to call repr() on 
it, as in "print repr(sys.argv[0])".  That would show you that it's 
merely the empty string ''.

> How does it know what the path of the argument is if it doesn't know
> what the argument is?  Seems a bit presumptive to assume that CWD is
> the path to a blank string...unless abspath presumes that anything you
> pass it is an executable, even if it's got no bytes...

os.path.abspath('') is merely returning the current directory.  It does 
seem sort of implicit, but it's doubtless behaviour that is counted on 
by many applications at this point, so I'm afraid it's unlikely to 
change, even if it wasn't such a good idea.  (And it might well be an 
excellent idea...)

-Peter




More information about the Python-list mailing list