Python os.chdir() 方法将当前工作目录更改为给定路径。在某些系统上,此命令有时用作 cd shell 命令的别名。
执行所有命令的目录称为当前工作目录。它可以是数据库文件、文件夹、库或目录。当前工作目录也称为当前工作目录或简称为工作目录。此方法不返回任何值。
语法
以下是 Python os.chdir() 方法的语法 -
os.chdir(path)
参数
- path - 这是要更改为新位置的目录的完整路径。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.chdir() 方法的用法。这里我们将当前工作目录更改为给定的路径 “/usr/tmp”。
import os
path = "/usr/tmp"
# change the directory
x = os.chdir(path)
print ("Directory changed successfully",x)
当我们运行上述程序时,它会产生以下结果——
Directory changed successfully /usr/tmp
示例 2
在这里,我们使用 getcwd() 方法来了解文件的当前工作目录。更改文件路径后,我们将使用 os.chdir() 方法验证当前工作目录的路径。
# importing the module
import os
# changing the current working directory to the given path
os.chdir('D:\Sarika Work')
# verifying the path using getcwd()
current = os.getcwd()
# printing the current working directory
print("The current working directory is:", current)
在执行上述代码时,我们得到以下输出 -
The current working directory is: D:\Sarika Work
示例 3
如果请求的目录不存在,则此方法将引发 FileNotFoundError。
# importing the modules
import sys
import os
# the current directory
cd = os.getcwd()
# some false directory
nd = 'nonexist_dir / temp'
# trying to insert to the non existing directory
try:
os.chdir(nd)
print("Changing the path to:", os.getcwd())
# Caching the exception
except:
print("Something went wrong with the given directory", sys.exc_info())
# handling with finally
finally:
print("Restore the path")
os.chdir(cd)
print("The current working directory is:", os.getcwd())
以下是上述代码的输出 -
Something went wrong with the given directory (<class 'FileNotFoundError'>, FileNotFoundError(2, 'The system cannot find the path specified'), <traceback object at 0x00000152D60B5640>)
Restore the path
The current working directory is: C:\Users\Lenovo\Desktop
Restore the path
The current working directory is: C:\Users\Lenovo\Desktop
示例 4
现在,我们正在将当前工作目录更改为主目录。
import os
print("The current working directory is:", os.getcwd())
# Changing the working directory to home directory
x = os.chdir(os.path.expanduser('~'))
print("The Current directory now is:",os.getcwd())
上述代码的输出如下 -
The current working directory is: C:\Users\Lenovo\Desktop
The Current directory now is: C:\Users\Lenovo
The Current directory now is: C:\Users\Lenovo