python什么是递归遍历_python递归遍历

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

主要用到的库 os

os.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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值