超好用的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操作简便很多

相关推荐
文人sec13 分钟前
使用python-pandas-openpyxl编写运营查询小工具
开发语言·python·pandas
hu_yuchen25 分钟前
问卷系统自动化测试报告
软件测试·python
百锦再1 小时前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
Ashlee_code1 小时前
经纪柜台系统解析:从今日国际金融动荡看证券交易核心引擎的变革
python·架构·系统架构·区块链·vim·柜台·香港券商
清空mega1 小时前
从零开始搭建 flask 博客实验(4)
后端·python·flask
咋吃都不胖lyh2 小时前
比较两个excel文件的指定列是否一致
爬虫·python·pandas
0小豆03 小时前
【系列开篇】从零构建智能字幕校准系统:一个AI+微服务的完整实战之旅
spring boot·python·nlp·微服务架构·实战项目·spacy·ai算法
周杰伦_Jay3 小时前
【主流开发语言深度对比】Python/Go/Java/JS/Rust/C++评测
开发语言·python·golang
盈电智控4 小时前
体力劳动反而更难被AI取代?物联网科技如何守护最后的劳动阵地
开发语言·人工智能·python
隔壁阿布都4 小时前
Spring Boot中的Optional如何使用
开发语言·spring boot·python