如何在Python Shell中查看/更改当前目录?
通过OS Python模块提供了一种与操作系统交互的可移植方法。该模块是默认Python库的一部分,包含用于查找和修改工作目录的工具。
本文介绍了以下内容。
- 如何获取当前工作目录:os.getcwd()
- 更改当前工作目录:os.chdir()
该__file__ 函数返回当前脚本文件(.py)的路径。
获取当前工作目录 - os.getcwd()
函数os.getcwd() 将Python当前工作目录的绝对路径作为字符串str返回。“获取当前工作目录”(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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP