📌  相关文章
📜  在 Python 中获取当前工作目录(1)

📅  最后修改于: 2023-12-03 14:51:06.458000             🧑  作者: Mango

在 Python 中获取当前工作目录

在进行文件操作时,获取当前工作目录是一个非常常见的需求。Python 中可以使用内置的 os 模块来获取当前工作目录。

方法一:使用 os 模块的 getcwd() 函数

Python 中 os.getcwd() 函数可以返回当前工作目录的绝对路径。

import os

# 获取当前工作目录
current_dir = os.getcwd()

# 输出当前工作目录
print("当前工作目录为:", current_dir)

输出结果为:

当前工作目录为: /Users/username/Projects
方法二:使用 os.path 模块的 realpath() 函数

实际上,还可以使用 os.path.realpath(__file__) 来获取当前文件的绝对路径,然后使用 os.path.dirname() 获取当前文件所在的目录,即为当前工作目录。

import os

# 获取当前工作目录
current_dir = os.path.dirname(os.path.realpath(__file__))

# 输出当前工作目录
print("当前工作目录为:", current_dir)

输出结果为:

当前工作目录为: /Users/username/Projects

这种方法更加灵活,可以准确地获取当前工作目录,无论是在命令行模式下运行还是在 IDE 中运行都没有问题。

总结

获取当前工作目录是 Python 中常见的操作之一,可以使用 os 模块的 getcwd() 函数或者 os.path 模块的 realpath()dirname() 函数来实现。在实际开发中,可以根据需要选择使用哪种方法来获取当前工作目录。