【pathlib】轻松处理Windows和Linux的路径操作(路径表示的斜杠与反斜杠之争)

使用 pathlib 库一键搞定!

from pathlib import Path

获取当前路径

cur_path = Path.cwd()

获取上层 or 上上层路径

cur_path.parent
cur_path.parent.parent

获取子目录 or 拼接目录

file_path = cur_path / 'file.txt' # 统一用 ‘/’ 斜杠分隔路径

paths = ['test', 'test.txt']
cur_path.joinpath(*paths)

获取文件名

cur_path.name # 文件名+扩展名
cur_path.stem # 文件名
cur_path.suffix # 扩展名

参考资料
https://blog.csdn.net/miantian180/article/details/81263443
https://www.cnblogs.com/poloyy/p/12435628.html
https://docs.python.org/zh-cn/3/library/pathlib.html

posted @ 2021-07-06 23:21  林東雨  阅读(802)  评论(0编辑  收藏  举报