Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.chdir() to relative home directory (/home/usr/)

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
like image 620
Seraf Avatar asked Jan 04 '23 17:01

Seraf


1 Answers

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.

like image 151
Dietrich Epp Avatar answered Jan 07 '23 07:01

Dietrich Epp