在 Python 中获取当前目录有两种方法:使用 os.getcwd() 获取直接保存当前工作目录路径。使用 pathlib.Path.cwd() 获取一个 Pathlib 对象,表示当前工作目录路径。

如何在 Python 中获取当前目录
在 Python 中获取当前目录有两种主要方法:
1. 使用 os.getcwd()
<code class="python">import os current_dir = os.getcwd() print(current_dir)</code>
2. 使用 pathlib.Path.cwd()
立即学习“Python免费学习笔记(深入)”;
<code class="python">from pathlib import Path current_dir = Path.cwd() print(current_dir)</code>
两者的区别
os.getcwd() 作为 CPython 解释器的内置函数,该函数将直接保存当前工作目录的路径,无论是在 Python 解释器内还是在外部设置。pathlib.Path.cwd() 会返回一个 Pathlib 对象,表示当前工作目录的路径。它更适合需要更高级的文件系统处理的功能,如路径操作和文件属性检查。如何使用
这两种方法都可以直接使用,无需任何参数。它们将返回当前工作目录的绝对路径。
例如:
<code class="python">import os
current_dir = os.getcwd()
print("Current Directory:", current_dir)</code>输出:
<code>Current Directory: /Users/username/Documents/project</code>
以上就是python当前目录怎么写的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号