Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

python - 如何在Python中更改目录(cd)?(How do I change directory (cd) in Python?)

cd as in the shell command to change the working directory.

(像在shell命令中一样cd来更改工作目录。)

How do I change the current working directory in Python?

(如何在Python中更改当前的工作目录?)

  ask by too much php translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

    (在无效路径上捕获异常(WindowsError,OSError)。)

    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 .

    (可以通过将您的chdir调用包装在上下文管理器中以异常安全的方式完成,就像Brian M. Hunt在他的答案中所做的那样。)

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.

(Python解释器也是如此。)

You cannot use os.chdir() to change the CWD of the calling process.

(您不能使用os.chdir()更改调用进程的CWD。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...