Python获取工作目录

Python获取工作目录教程

每个运行在计算机上的程序,都有一个 “当前工作目录”,当前目录又称为值班目录或工作目录。它是当前用户正在使用的文件的目录,或者说是程序的可执行文件所在的目录。

getcwd函数详解

语法

import os os.getcwd()

返回值

返回当前目录。

说明

在使用 getcwd 函数获取当前工作目录之前,我们首先需要导入 os 包。getcwd 函数不需要传递任何 函数参数,以 返回值 的形式返回当前目录。

案例

获取当前目录

使用 getcwd 函数获取当前目录

print("嗨客网(www.haicoder.net)") import os cpath = os.getcwd() print("Path =", cpath) os.chdir("C:") cpath = os.getcwd() print("Path =", cpath)

程序运行后,控制台输出如下:

01_Python getcwd函数.png

我们首先,使用 getcwd 函数获取了当前的工作目录,接着,使用 chdir 函数手动切换了工作目录,接着,再次使用 getcwd 函数获取当前工作目录,当前工作目录已经改变。

Python获取工作目录总结

在 Python 中,获取当前工作目录使用 getcwd 函数,getcwd 函数会返回当前的工作目录。