strange interaction between open and cwd

Chris Rebert clp2 at rebertia.com
Mon May 3 09:18:55 EDT 2010


On Mon, May 3, 2010 at 5:42 AM, Baz Walter <bazwal at ftml.net> wrote:
> Python 2.6.4 (r264:75706, Mar  7 2010, 02:18:40)
> [GCC 4.4.1] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import os
>>>> os.mkdir('/home/baz/tmp/xxx')
>>>> f = open('/home/baz/tmp/abc.txt', 'w')
>>>> f.write('abc')
>>>> f.close()
>>>> os.chdir('/home/baz/tmp/xxx')
>>>> os.getcwd()
> '/home/baz/tmp/xxx'
>>>> os.rmdir(os.getcwd())
>>>> os.getcwd()
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> OSError: [Errno 2] No such file or directory
>>>> open('../abc.txt').read()
> 'abc'
>>>>
>
> can anybody explain how python is able to read the file at the end of this
> session?
<snip>
> but how can python determine the
> parent directory of a directory that no longer exists?

Whether or not /home/baz/tmp/xxx/ exists, we know from the very
structure and properties of directory paths that its parent directory
is, *by definition*, /home/baz/tmp/ (just chop off everything after
the second-to-last slash). I would assume this is what happens
internally.
How exactly this interacts with, say, moving the directory to a new
location rather than deleting it, I don't know; again, it would quite
likely be platform-specific.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list