strange interaction between open and cwd

Baz Walter bazwal at ftml.net
Mon May 3 08:42:13 EDT 2010


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? i'm guessing it's a platform specific thing as i'm pretty 
sure the above sequence of commands wouldn't work on windows (i.e. 
attempting to remove the cwd would produce an error). but how can python 
determine the parent directory of a directory that no longer exists?

this actually caused a bug for me. i was trying to ensure that my 
program always resolved any file-names given on the command line by 
using os.path.realpath(). i had assumed that if realpath failed, then 
open would also fail - but not so!



More information about the Python-list mailing list