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. 遞歸遍歷根目錄下的制定文件.
# -*- 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()

歡迎加入CodeTribes大家庭。
CodeTribes羣號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章