Python os.chdir() 方法将当前工作目录更改为给定路径。在某些系统上,此命令有时用作 cd shell 命令的别名。
执行所有命令的目录称为当前工作目录。它可以是数据库文件、文件夹、库或目录。当前工作目录也称为当前工作目录或简称为工作目录。此方法不返回任何值。
语法
以下是 Python os.chdir() 方法的语法 -
参数
- path - 这是要更改为新位置的目录的完整路径。
返回值
此方法不返回任何值。
示例 1
以下示例显示了 Python os.chdir() 方法的用法。这里我们将当前工作目录更改为给定的路径 “/usr/tmp”。
当我们运行上述程序时,它会产生以下结果——
Directory changed successfully /usr/tmp
示例 2
在这里,我们使用 getcwd() 方法来了解文件的当前工作目录。更改文件路径后,我们将使用 os.chdir() 方法验证当前工作目录的路径。
在执行上述代码时,我们得到以下输出 -
The current working directory is: D:\Sarika Work
示例 3
如果请求的目录不存在,则此方法将引发 FileNotFoundError。
以下是上述代码的输出 -
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
现在,我们正在将当前工作目录更改为主目录。
上述代码的输出如下 -
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