How do I change the working directory in Python?

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

    You can change the working directory with:

    import os
    
    os.chdir(path)
    

    There are two best practices to follow when using this method:

    1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
    2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

    Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

提交回复
热议问题