6

Is there a way to use os.chdir() to go to relative user folder?

I'm making a bash and the only issue I found is the cd ~, arg[0] is undefined since I'm using this cd functions:

def cd(args):
    os.chdir(args[0])
    return current_status

Which I want to change to

def cd(args):
    if args[0] == '~':
        os.chdir('/home/') 
# Here I left it to /home/ since I don't know how 
# to get the user's folder name
    else:
        os.chdir(args[0])
    return current_status
Seraf
  • 850
  • 1
  • 17
  • 34

1 Answers1

12

No, os.chdir won't do that, since it is just a thin wrapper around a system call. Consider that ~ is actually a legal name for a directory.

You can, however, use os.expanduser to expand ~ in a path.

def cd(path):
    os.chdir(os.path.expanduser(path))

Note that this will also expand ~user to the home directory for user.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • Which is more broadly applicable too, it handles paths relative to the user home (`~/private/dir`) and (to an extent) handles other user home relative paths too (`~otheruser/public/dir`). – ShadowRanger Jan 19 '17 at 03:38
  • 1
    Why is ~ returning path not found error? I'll review my code and edit my question. – Seraf Jan 19 '17 at 03:44