Returning the path of a file
Steven D. Majewski
sdm7g at virginia.edu
Fri Jan 5 12:53:14 EST 2001
On Fri, 5 Jan 2001, Daniel Klein wrote:
> I've search the Beazley book as well as the Python reference materials
> and can't find answers to these two basically simple questions:
>
> 1) How to return the path of a file previously opened in read-only
> mode?
>
> myfile = open("foo")
>
> I know I can do something like
>
> os.getcwd()
>
> and this is where 'myfile' is, but if the file was opened by some
> other method, I would like to be able to interrogate where it was
> opened from.
>
>
file.name gives you the name used in opening the file.
If you open it with with no path or a relative path,
that's what you'll get back:
>>> file = open( 'test.py' )
>>> file.name
'test.py'
If you open it with the full pathname, you'll get that back:
>>> import os
>>> file2 = open( os.path.abspath('test.py' ))
>>> file2.name
'/Users/sdm7g/test.py'
And if you need to do this a lot and you can't remember to use the
absolute path all the time, you can redefine the open function to
do it for you:
>>> import __builtin__
>>> import os
>>> def open( filename, *args ):
... return apply( __builtin__.open, ( os.path.abspath(filename),) + args )
-- Steve Majewski <sdm7g at Virginia.EDU>
More information about the Python-list
mailing list