How do I change the working directory in Python?

前端 未结 14 1171
天涯浪人
天涯浪人 2020-11-22 01:59

cd is the shell command to change the working directory.

How do I change the current working directory in Python?

14条回答
  •  悲哀的现实
    2020-11-22 02:33

    cd() is easy to write using a generator and a decorator.

    from contextlib import contextmanager
    import os
    
    @contextmanager
    def cd(newdir):
        prevdir = os.getcwd()
        os.chdir(os.path.expanduser(newdir))
        try:
            yield
        finally:
            os.chdir(prevdir)
    

    Then, the directory is reverted even after an exception is thrown:

    os.chdir('/home')
    
    with cd('/tmp'):
        # ...
        raise Exception("There's no place like home.")
    # Directory is now back to '/home'.
    

提交回复
热议问题