How do I change the working directory in Python?

前端 未结 14 1170
天涯浪人
天涯浪人 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:32

    os.chdir() is the Pythonic version of cd.

    0 讨论(0)
  • 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'.
    
    0 讨论(0)
提交回复
热议问题