Welcome, guest | Sign In | My Account | Store | Cart

Dealing with directory paths which start with ~ which are passed as paramaters, to os module functions.

Here is what I think python doesn't do for me:

>>> import os
# suppose my home = curdir = /home/rv
>>> os.path.abspath('.') 
'/home/rv'

Now if I want to go to folder /home/rv/test if there is no folder by name /home/rv/~/test/

# This is what happens by default.
>>> os.path.abspath('~/test')
'/home/rv/~/test'

>>> os.chdir('/home/rv/some/dir')
# doesn't matter if the resulting path exists or not.
>>> os.path.abspath('~/test')
'home/rv/some/dir/~/test'

This would be more sensible I guess:

# if /home/rv/~/test doesn't exist
>>> os.path.abspath('~/test')
'/home/rv/test'
Python, 11 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import os

# i am big on absolute paths, so i made it return an absolute path
# also that makes the results clearer.
def full_path(dir_):
    if dir_[0] == '~' and not os.path.exists(dir_):
        dir_ = os.path.expanduser(dir_)
    return os.path.abspath(dir_)

if __name__ == '__main__':
    print os.path.abspath(full_path('~/test')) # returns /home/rv/~/test if it exists or else it outputs /home/rv/test

1 comment

david.gaarenstroom 11 years, 5 months ago  # | flag

I don't see why you'd check for dir_[0] and os.path.exists[dir_] The first one is already handled by expandpath, and the latter is just plain dangerous, because that is not how it is handled normally, e.g. by the shell.

So just use:

os.path.abspath(os.path.expandpath('~/test'))
Created by roopeshv on Wed, 16 Jun 2010 (PSF)
Python recipes (4591)
roopeshv's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks