python递归遍历
2017-12-26 22:07
176 查看
使用python对制定文件夹下制定后缀的文件进行遍历.
主要用到的库 osos.path.exists(path):判断路径是不是存在
os.makedirs:创建文件夹
os.path.join:合并路径
os.path.isfile:判断是文件夹还是文件
(path, extension) = os.path.splitext(source_file):路径和文件名
os.path库中还有很多好用的函数,如果有需要请自行了解
递归遍历根目录下的制定文件.
# -*- coding: utf-8 -*- __author__ = 'big_centaur' #采用递归遍历的方式遍历图片 import os from PIL import Image # 要处理的目录 folder = 'datasets' def recurve_opt(root_path): for file in os.listdir(root_path): target_file = os.path.join(root_path, file) if os.path.isfile(target_file): (path, extension) = os.path.splitext(target_file) if extension == '.jpg' or extension == '.png': # Do something 此处我用于把图片转为灰度图像 # image = Image.open(target_file).convert('L') # image.save(target_file) # print(target_file) else: recurve_opt(target_file) def main(): recurve_opt(folder) if __name__ == '__main__': main()
递归遍历并按照同样的目录架构 拷贝 到制定文件夹
# -*- coding: utf-8 -*- __author__ = 'big_centaur' #采用递归遍历的方式遍历图片 def recurve_opt(root_1, root_2): if not os.path.exists(root_2): os.makedirs(root_2) for file in os.listdir(root_1): source_file = os.path.join(root_1, file) target_file = os.path.join(root_2, file) if os.path.isfile(source_file): (path, extension) = os.path.splitext(source_file) if extension == '.jpg' or extension == '.png': # shutil.copy(source_file, target_file) # do something 此处我用于直接复制图像 else: recurve_opt(source_file, target_file) def main(): floder_1 = 'datasets/captcha/test_adjust' floder_2 = 'datasets/captcha/test_adjust_remove_extar' # floder_1:源文件夹 floder_2:目的文件 遍历源文件下的所有文件,按照原来的顺序存在目的文件夹中 recurve_opt(floder_1, floder_2) if __name__ == '__main__': main()
相关文章推荐
- Python实现递归遍历文件夹并删除文件
- python小例子之1 -- 递归遍历目录
- Python 递归,遍历文件夹有层次感
- Python Selenium递归遍历frame定位元素
- Python:递归遍历目录,统计目录大小,并以列表的形式返回所有py文件
- Python递归遍历列表及输出的实现方法
- 二叉树的前序,中序,后续,递归及非递归遍历的python实现
- python 递归遍历文件夹
- 二叉树的前序、中序、后序遍历的非递归方法 python
- python小例子之1 -- 递归遍历目录
- python获取父类的子类(遍历,递归),并循环执行所有子类的某一方法
- 03-python文件(文件夹复制练习)------使用递归遍历,广度遍历(队列),深度遍历(栈)
- python - 自定义一个递归函数用于递归遍历指定目录下的所有文件
- Python数据结构之二叉树(涵盖了构建、删除、查找、字典转换、非递归与递归遍历等)
- Python 用栈模拟递归,遍历文件夹
- python 递归遍历文件夹,并打印满足条件的文件路径实例
- Python实现递归遍历文件夹并删除文件
- Python脚本- 递归遍历文件夹,获取指定扩展名文件,修改文件内容
- python递归遍历文件夹检查文件
- python三种遍历目录的方法递归 栈 和队列