python递归遍历

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

  1. 主要用到的库 os

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

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

  2. 递归遍历根目录下的制定文件.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    # -*- 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()
  3. 递归遍历并按照同样的目录架构 拷贝 到制定文件夹

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    # -*- 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()
------本文结束感谢阅读------