How do I change the working directory in Python?

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

    If you're using a relatively new version of Python, you can also use a context manager, such as this one:

    from __future__ import with_statement
    from grizzled.os import working_directory
    
    with working_directory(path_to_directory):
        # code in here occurs within the directory
    
    # code here is in the original directory
    

    UPDATE

    If you prefer to roll your own:

    import os
    from contextlib import contextmanager
    
    @contextmanager
    def working_directory(directory):
        owd = os.getcwd()
        try:
            os.chdir(directory)
            yield directory
        finally:
            os.chdir(owd)
    

提交回复
热议问题