Python遍历文件夹的两种方法比较
来源:互联网 发布:平板软件市场 编辑:程序博客网 时间:2024/05/20 20:58
Python遍历文件夹的两种方法比较
转自:点击打开链接
# -*- coding: utf-8 -*- import os def Test1(rootDir): list_dirs = os.walk(rootDir) for root, dirs, files in list_dirs: for d in dirs: print os.path.join(root, d) for f in files: print os.path.join(root, f)第二种:使用os.listdir:
# -*- coding: utf-8 -*- import os def Test2(rootDir): for lists in os.listdir(rootDir): path = os.path.join(rootDir, lists) print path if os.path.isdir(path): Test2(path)
E:\TEST │--A │ │--A-A │ │ │--A-A-A.txt │ │--A-B.txt │ │--A-C │ │ │--A-B-A.txt │ │--A-D.txt │--B.txt │--C │ │--C-A.txt │ │--C-B.txt │--D.txt │--E
下面通过运行如下代码:
Test1('E:\TEST') print '=======================================' Test2('E:\TEST')
输出结果为:
>>> E:\TEST\A E:\TEST\C E:\TEST\E E:\TEST\B.txt E:\TEST\D.txt E:\TEST\A\A-A E:\TEST\A\A-C E:\TEST\A\A-B.txt E:\TEST\A\A-D.txt E:\TEST\A\A-A\A-A-A.txt E:\TEST\A\A-C\A-B-A.txt E:\TEST\C\C-A.txt E:\TEST\C\C-B.txt ======================================= E:\TEST\A E:\TEST\A\A-A E:\TEST\A\A-A\A-A-A.txt E:\TEST\A\A-B.txt E:\TEST\A\A-C E:\TEST\A\A-C\A-B-A.txt E:\TEST\A\A-D.txt E:\TEST\B.txt E:\TEST\C E:\TEST\C\C-A.txt E:\TEST\C\C-B.txt E:\TEST\D.txt E:\TEST\E >>>可以看出,对于第一种方法,输出总是先文件夹后文件名的,对于第二种,则是按照目录树结构以及按照首字母排序进行输出的。
from PIL import Imageimport osimport os.pathdef change_format(rootDir):for root, dirs, files in os.walk(rootDir):for file in files:if os.path.splitext(file)[1] == '.ppm':im = Image.open(os.path.join(root, file))filename = os.path.join(root, file)im.save(os.path.splitext(filename)[0] + '.jpg', 'JPEG')if __name__ == '__main__':_dir = "your directory"change_format(_dir)
root 为 path(一直到file名字(除去文件名字)),file只是文件名字加上扩展名
此处os.path.join(root,file)为absolute path,os.path.splitext(file)[1]为扩展名(os.path.splitext(file)[1][1:]为ppm不带.),os.path.splitext(file)[0]为文件名
阅读全文
0 0
- Python遍历文件夹的两种方法比较
- Python遍历文件夹的两种方法比较
- Python遍历文件夹的两种方法比较
- Python遍历文件夹的两种方法比较
- python ── 遍历dict的两种方法比较
- python两种遍历字典(dict)的方法比较
- python两种遍历字典(dict)的方法比较
- java遍历文件夹的两种方法
- 遍历文件夹的两种方法
- Java遍历文件夹的两种方法
- python遍历文件夹——两种遍历本地文件记录文件夹个数、文件数及文件大小的方法
- 遍历文件夹的方法比较
- HashMap的两种遍历方法比较
- Python 遍历文件夹的方法:
- python遍历数组的两种方法
- python遍历数组的两种方法
- python编程细节──遍历dict的两种方法比较
- 递归实现遍历文件夹的两种方法
- Handler机制解析(源码角度)
- java实现加密电话号码,有具体的加密流程注释
- mac 上安装 nvm 遇到的坑
- 堆排序原理及算法实现(最大堆)
- USB2.0之data PID
- Python遍历文件夹的两种方法比较
- Linux之chattr(+i)
- LINUX定时清理文件定时任务
- MongDB创建索引
- 推荐书籍--留点时间回到精神的家园
- 598. Range Addition II (Easy)
- Numpy1
- 1. Two Sum
- 几种int类型的范围