如何在 Python shell 中知道/更改当前目录?
programmingpythonserver side programming
通过 OS Python 模块提供了一种与操作系统交互的可移植方法。该模块是默认 Python 库的一部分,包含用于定位和修改工作目录的工具。
本文介绍了以下内容。
- 如何获取当前工作目录:os.getcwd()
- 更改当前工作目录:os.chdir()
__file__ 函数返回当前脚本文件 (.py) 的路径。
获取当前工作目录 - os.getcwd()
函数 os.getcwd() 以字符串 str 形式返回 Python 当前工作目录的绝对路径。 "获取当前工作目录"(getcwd) 是指使用 print() 和 getcwd() 在操作系统中打印当前工作目录的能力。
返回的字符串中省略了尾部斜杠字符。
示例
以下是获取当前工作目录的示例:
# Importing the module import os # Getting the current working directory cwd = os.getcwd() # Printing the current working directory print("Th Current working directory is: {0}".format(cwd)) # Printing the type of the returned object print("os.getcwd() returns an object of type: {0}".format(type(cwd)))
输出
以下是上述代码的输出:
The Current working directory is: C:\Users\Lenovo\Desktopos.getcwd() returns an object of type: class 'str'> os.getcwd() returns an object of type:
更改当前工作目录:os.chdir()
使用 Python 中的 chdir() 函数更改当前工作目录。
要更改到的目录的路径是该方法允许的唯一参数。您可以使用绝对路径或相对路径参数。
示例
以下是更改当前工作目录的示例:
# Importing the module import os # Printing the current working directory print("The Current working directory is: {0}".format(os.getcwd())) # Changing the current working directory os.chdir('C:\Users\Lenovo\Downloads\Works') # Print the current working directory print("The Current working directory now is: {0}".format(os.getcwd()))
输出
以下是上述代码的输出:
The Current working directory is: C:\Users\Lenovo\Desktop The Current working directory now is: C:\Users\Lenovo\Downloads\Works
注意− 如果未将目录作为参数提供给 chdir() 方法,则会引发 NotADirectoryError 异常。如果未找到提供的目录,则会引发 FileNotFoundError 异常。如果运行脚本的用户没有所需的权限,则会引发 PermissionError 异常。
示例
# Import the os module import os path = 'C:\Users\Lenovo\Downloads\Works' try: os.chdir(path) print("The Current working directory is: {0}".format(os.getcwd())) except FileNotFoundError: print("Directory: {0} does not exist".format(path)) except NotADirectoryError: print("{0} is not a directory".format(path)) except PermissionError: print("No permissions to change to {0}".format(path))
输出
以下是上述示例的输出:
The Current working directory is: C:\Users\Lenovo\Downloads\Works