Python os.getcwd() 方法:完整指南
getcwd 代表“获取当前工作目录”,而提供相同输出的 Unix 命令是 pwd 代表“打印工作目录”。 pwd 命令帮助我们在终端或 CMD 中打印当前工作目录。
Python os.getcwd()
getcwd() 是一个内置的 Python os 模块方法,它返回当前工作目录。 要使用 Python 命令获取当前工作目录,请使用 os.getcwd() 函数。
要更改 Python 中的当前工作目录,请使用 os.chdir() 方法。
句法
os.getcwd()
参数
os.getcwd() 函数不接受任何参数。
返回值
os.getcwd() 方法返回一个代表当前工作目录的字符串。
例子
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
输出
Current working directory: /Users/krunallathiya/Desktop/Code/R
您可以看到我们的文件 app.py 位于 /Users/krunallathiya/Desktop/Code/R 文件夹中。
如何在 Python 中更改当前工作目录
要更改 Python 中的当前工作目录,请使用 os.chdir() 方法。 os.chdir() 函数将当前工作目录更改为指定路径。 chdir 代表“更改目录”。
您可以在参数中指定目标路径。 目标路径可以是相对路径或绝对路径。
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
os.chdir('../../')
ncwd = os.getcwd()
print("Current working directory:", ncwd)
输出
Current working directory: /Users/krunallathiya/Desktop/Code/R
Current working directory: /Users/krunallathiya/Desktop
您可以看到我们将目标路径定义为相对路径。 ‘../’ 对于在目录中向上移动很有用。
这就是在 Python 中获取当前目录的过程。
相关文章
Python 操作系统
Python os.listdir
Python os.walk
如何在 Python 中设置环境变量
帖子 Python os.getcwd() 方法:完整指南首先出现在 AppDividend 上。