cd
是用于改变工作目录的 shell 命令。
Python 中如何更改当前的工作目录?
import os
os.chdir(path)
你应该小心,改变目录可能会导致你的代码在新位置应用破坏性的改变。更糟糕的是,在改变目录后不要捕获诸如WindowsError
和OSError
的异常,因为这可能意味着破坏性的改变被应用在旧的位置!
如果你使用的是Python 3.11或更新版本,那么考虑使用这个上下文管理器,以确保在完成后返回到原始的工作目录:
from contextlib import chdir
with chdir(path):
# do stuff here
os.chdir()
来更改调用进程的当前工作目录。os.chdir()
**。(你很可能不知道。) - Cecil Curryos.chdir("C:/path/to/location")
。 - Josiahr'C:\path\to\location'
。 - Burakalias myAlias="cd ..;./myPythonScript.py;cd ~"
。由于别名不是技术上的脚本,所以它可以工作。 - Brōtsyorfuzthrāxcd
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)
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.
__enter__
的最后加上return self
。这样你就可以用with cd('foo') as cm:
进行操作,并将以前的目录作为cm.savedPath
访问到。 - Sam FAttribute 'savedPath' defined outside __init__ [attribute-defined-outside-init]
- alperwith cd("~/Library"):
块内部使用 return
,它仍然有效吗? - alperwith
块的全部意义:确保无论如何都会调用 __exit__
,即使你使用了 return
。 - Iziminza__init__
中定义属性,比如self.savedPath = None
。 - Iziminzacd()
很容易使用生成器和装饰器来编写。
from contextlib import contextmanager
import os
@contextmanager
def cd(newdir):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
然后,即使抛出异常,目录也会被还原:
os.chdir('/home')
with cd('/tmp'):
# ...
raise Exception("There's no place like /home.")
# Directory is now back to '/home'.
yield
而不是 return
?这是否应该是一个生成器? - EKonstry
块中使用 chdir
吗? - Rainbow Fossil如果您正在使用相对较新的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)
正如其他人指出的那样,上面所有的解决方案都只会改变当前进程的工作目录。当您回到Unix shell时,这将会丢失。如果非常需要,您可以使用这个可怕的黑客方法更改Unix上的父shell目录:
def quote_against_shell_expansion(s):
import pipes
return pipes.quote(s)
def put_text_back_into_terminal_input_buffer(text):
# use of this means that it only works in an interactive session
# (and if the user types while it runs they could insert characters between the characters in 'text'!)
import fcntl, termios
for c in text:
fcntl.ioctl(1, termios.TIOCSTI, c)
def change_parent_process_directory(dest):
# the horror
put_text_back_into_terminal_input_buffer("cd "+quote_against_shell_expansion(dest)+"\n")
os.chdir()
是 Python 中的 cd
命令。
os.chdir()
是正确的方式。
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.path.join(os.path.abspath(os.path.curdir),u'subfolder'))
- 或者呢? - Mr_and_Mrs_Dos.getcwd()
- Martin Thoma