How do I change the working directory in Python?

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

    Here's an example of a context manager to change the working directory. It is simpler than an ActiveState version referred to elsewhere, but this gets the job done.

    Context Manager: cd

    import os
    
    class cd:
        """Context manager for changing the current working directory"""
        def __init__(self, newPath):
            self.newPath = os.path.expanduser(newPath)
    
        def __enter__(self):
            self.savedPath = os.getcwd()
            os.chdir(self.newPath)
    
        def __exit__(self, etype, value, traceback):
            os.chdir(self.savedPath)
    

    Or try the more concise equivalent(below), using ContextManager.

    Example

    import subprocess # just to call an arbitrary command e.g. 'ls'
    
    # enter the directory like this:
    with cd("~/Library"):
       # we are in ~/Library
       subprocess.call("ls")
    
    # outside the context manager we are back wherever we started.
    

提交回复
热议问题