cd是用于更改工作目录的shell命令。
如何更改Python中的当前工作目录?
cd是用于更改工作目录的shell命令。
如何更改Python中的当前工作目录?
当前回答
os.chdir()是cd的Python版本。
其他回答
如果您使用的是相对较新的Python版本,也可以使用上下文管理器,例如:
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
更新
如果你喜欢自己动手:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(directory):
owd = os.getcwd()
try:
os.chdir(directory)
yield directory
finally:
os.chdir(owd)
如果您使用spyder和love GUI,只需单击屏幕右上角的文件夹按钮,即可浏览您希望作为当前目录的文件夹/目录。完成此操作后,您可以转到spyder IDE中窗口的文件资源管理器选项卡,您可以看到那里存在的所有文件/文件夹。检查当前工作目录转到spyder IDE的控制台,只需键入
pwd
它将打印与您之前选择的路径相同的路径。
import os
abs_path = 'C://a/b/c'
rel_path = './folder'
os.chdir(abs_path)
os.chdir(rel_path)
您可以将两者与os.chdir(abs_path)或os.chdir(rel_path)一起使用,不需要调用os.getcwd()来使用相对路径。
我会这样使用os.chdir:
os.chdir("/path/to/change/to")
顺便说一句,如果需要计算当前路径,请使用os.getcwd()。
更多信息请点击此处
下面是一个上下文管理器更改工作目录的示例。它比其他地方提到的ActiveState版本更简单,但这可以完成任务。
上下文管理器: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)
或者使用ContextManager尝试更简洁的等效方法(如下)。
实例
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.