python递归遍历

作者: ciantian | 来源:发表于2017-12-26 22:05 被阅读52次

使用python对制定文件夹下制定后缀的文件进行遍历.

  1. 主要用到的库 os
  • os.path.exists(path):判断路径是不是存在
  • os.makedirs:创建文件夹
  • os.path.join:合并路径
  • os.path.isfile:判断是文件夹还是文件
  • (path, extension) = os.path.splitext(source_file):路径和文件名

os.path库中还有很多好用的函数,如果有需要请自行了解

  1. 递归遍历根目录下的制定文件.
# -*- 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()
  1. 递归遍历并按照同样的目录架构 拷贝 到制定文件夹
# -*- 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 3 实现:

  • python递归遍历

    使用python对制定文件夹下制定后缀的文件进行遍历. 主要用到的库 os os.path.exists(path...

  • 二叉树先序、中序、后序遍历 递归与非递归 Python实现 1.先序遍历:根节点->左子树->右子树 2.中序遍历...

  • 树的遍历

    节点结构: 先序遍历 递归 非递归 后序遍历 递归 非递归 中序遍历 递归 非递归 层序遍历 类库 有了上述遍历算...

  • 数据结构-树以及深度、广度优先遍历

    数据结构-树以及深度、广度优先遍历(递归和非递归,python实现)[https://www.cnblogs.co...

  • 二叉树的遍历

    非递归前序遍历 非递归中序遍历 非递归后序遍历 层序遍历

  • python目录的遍历方法

    python目录的遍历两种方法 其一:递归法 其二:python内置函数walk

  • 二叉树三种遍历的实现(递归)

    前序递归遍历算法:访问根结点-->递归遍历根结点的左子树-->递归遍历根结点的右子树 中序递归遍历算法:递归遍历根...

  • 二叉树的前中后三种遍历(递归、非递归和Morris)

    前序遍历 递归版本 非递归版本 中序遍历 递归版本 非递归版本 Morris 遍历待补充 后序遍历 递归版本 非递...

网友评论

    本文标题:python递归遍历

    本文链接:https://www.haomeiwen.com/subject/bgoegxtx.html