python遞歸遍歷

使用python對制定文件夾下制定后綴的文件進行遍歷.

  1. 主要用到的庫 os
  • os.path.exists(path):判斷路徑是不是存在
  • os.makedirs:創(chuàng)建文件夾
  • os.path.join:合并路徑
  • os.path.isfile:判斷是文件夾還是文件
  • (path, extension) = os.path.splitext(source_file):路徑和文件名

os.path庫中還有很多好用的函數(shù),如果有需要請自行了解

  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 此處我用于把圖片轉(zhuǎn)為灰度圖像
                # 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. 遞歸遍歷并按照同樣的目錄架構(gòu) 拷貝 到制定文件夾
# -*- 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()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容