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

【持续更新】

最新文章

  1. SQLite一些函数用法
  2. 尚学堂Spring视频教程(三):Spring Core中的其他特性
  3. 【BZOJ】1100: [POI2007]对称轴osi
  4. Entity Framework 第九篇 关于自增列的事务处理
  5. 菜单滑动-menu swipe
  6. webview--网络超时
  7. HDOJ 2018 母牛的故事
  8. 无法启动outlook mapi
  9. UVA 10140 - Prime Distance(数论)
  10. AspNetCore-MVC实战系列(三)之个人中心
  11. vijos1057题解
  12. linux几种时间函数总结
  13. Linux 典型应用之常用命令
  14. 游戏服务器学习笔记 5———— twisted Perspective Broker 透明代理
  15. zabbix 自定义监控nginx
  16. mysql优化不可不做的事情
  17. C_文件包含.h文件和包含.c文件总结
  18. 转载:mysql 操作总结 INSERT和REPLACE
  19. xshell显示隐藏窗口页签
  20. [Todo] C++并发编程学习

热门文章

  1. 用python进行加密和解密——我看刑
  2. Could not transfer artifact xxx from/to xxx解决方案
  3. 记一次 .NET 某新能源系统 线程疯涨 分析
  4. 交替方向乘子法(Alternating Direction Multiplier Method,ADMM)
  5. Solution -「线段树」题目集合
  6. 常用的函数式接口_Predicate接口_默认方法and和Predicate接口练习_集合接口筛选
  7. VGA显示原理
  8. SP8496 NOSQ - No Squares Numbers 题解
  9. java后端分片上传接口
  10. 利用本地HTTPS模拟环境为FastAPI框架集成FaceBook社交三方登录