超好用的python标准库——pathlib

官方文档

os和pathlib对比

  • 判断当前目录下的目录
python 复制代码
>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[WindowsPath('data')]
python 复制代码
>>>[i for i in glob.glob("*") if os.path.isdir(i)]
['data']
  • 返回当前目录下的所有文件(包括子文件)
python 复制代码
>>>list(p.glob("**/*"))
python 复制代码
>>>list(glob.glob("**/*", recursive=True))
python 复制代码
使用os包需要递归,比较复杂
  • 路径拼接
python 复制代码
>>>p = p/'__init__.py'
WindowsPath('__init__.py')
python 复制代码
>>>os.path.join('.', '__init__.py')
.\__init__.py
  • 打开文件
python 复制代码
with p.open() as f:
    f.read()

以上都是比较常用的操作,更多操作请看官方文档,作对比后个人感觉确实比os操作简便很多

相关推荐
2301_782040455 分钟前
CSS Flex布局中如何实现导航栏与Logo的左右分布_利用justify-content- space-between
jvm·数据库·python
yaoxin52112312 分钟前
400. Java 文件操作基础 - 使用 Buffered Stream I/O 读取文本文件
java·开发语言·python
用户8356290780511 小时前
使用 Python 自动创建 Excel 折线图
后端·python
小白学大数据1 小时前
面向大规模爬取:Python 全站链接爬虫优化(过滤 + 断点续爬)
开发语言·爬虫·python
WL_Aurora2 小时前
【每日一题】贪心
python·算法
IT策士2 小时前
Python 中间件系列:redis 深入浅出
redis·python·中间件
Dxy12393102162 小时前
Python Pillow库:`img.format`与`img.mode`的区别详解
开发语言·python·pillow
༒࿈南林࿈༒3 小时前
刺猬猫小说下载
python·js逆向
.柒宇.3 小时前
AI-Agent入门实战-AI私厨
人工智能·python·langchain·agent·fastapi
默子昂3 小时前
langchain 基本使用
开发语言·python·langchain