示例 1:使用 pathlib 模块
import pathlib
# path of the given file
print(pathlib.Path("my_file.txt").parent.absolute())
# current working directory
print(pathlib.Path().absolute())
输出
/Users/username /Users/username
使用 pathlib 模块,你可以获取当前工作目录。
- 在
Path()方法中传入文件名。 parent返回路径的逻辑父目录,absolute()返回文件的绝对路径。pathlib.Path().absolute()返回当前工作目录。
示例 2:使用 os 模块
import os
# path of the given file
print(os.path.dirname(os.path.abspath("my_file.txt")))
# current working directory
print(os.path.abspath(os.getcwd()))
输出
/Users/username /Users/username
你可以使用 os 模块做同样的事情。
- 使用
abspath()方法获取绝对路径。 getcwd()返回当前工作目录。
另请阅读
