[Python]-os模块-文件读取
2024-10-19 21:40:46
import os
在Python中,os模块用来处理文件路径,比较方便。
os读取文件
在读取文件过程中,最常用的几个功能如下:
os.listdir()
获取此目录下的所有目录名,并且存为列表。在遍历文件夹时非常好用。
file_list = os.listdir(top_path)
os.path.join()
合并文件路径,在连接处自动添加'/'
。结合上一个os.listdir()
就可以对子文件夹实现遍历。
file_list = os.listdir(top_path)
for son_file in file_list:
son_path = os.path.join(top_path, son_file)
os.path.split()
把文件路径从最后一个'/'
分开,存为一个list。
可以理解为os.path.join()的反向操作。
split_list = os.path.split(son_path)
#split_path = [top_path, son_file]
逐行读取txt文件中存储的路径
with open(txt_path, 'r') as f:
content = f.readlines()
for line in content:
path = line.strip()
os确保文件夹存在
if not os.path.exists(path): # 如果不存在就创建文件夹
os.mkdir(path)
关于OS的其他用法,这篇笔记比较详细:http://www.ityouknow.com/python/2019/10/09/python-os-demonstration-026.html
【持续更新】
最新文章
- SQLite一些函数用法
- 尚学堂Spring视频教程(三):Spring Core中的其他特性
- 【BZOJ】1100: [POI2007]对称轴osi
- Entity Framework 第九篇 关于自增列的事务处理
- 菜单滑动-menu swipe
- webview--网络超时
- HDOJ 2018 母牛的故事
- 无法启动outlook mapi
- UVA 10140 - Prime Distance(数论)
- AspNetCore-MVC实战系列(三)之个人中心
- vijos1057题解
- linux几种时间函数总结
- Linux 典型应用之常用命令
- 游戏服务器学习笔记 5———— twisted Perspective Broker 透明代理
- zabbix 自定义监控nginx
- mysql优化不可不做的事情
- C_文件包含.h文件和包含.c文件总结
- 转载:mysql 操作总结 INSERT和REPLACE
- xshell显示隐藏窗口页签
- [Todo] C++并发编程学习
热门文章
- 用python进行加密和解密——我看刑
- Could not transfer artifact xxx from/to xxx解决方案
- 记一次 .NET 某新能源系统 线程疯涨 分析
- 交替方向乘子法(Alternating Direction Multiplier Method,ADMM)
- Solution -「线段树」题目集合
- 常用的函数式接口_Predicate接口_默认方法and和Predicate接口练习_集合接口筛选
- VGA显示原理
- SP8496 NOSQ - No Squares Numbers 题解
- java后端分片上传接口
- 利用本地HTTPS模拟环境为FastAPI框架集成FaceBook社交三方登录