简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM