1. 程式人生 > >python遍歷讀取檔案下的所有指定型別的檔案

python遍歷讀取檔案下的所有指定型別的檔案

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

# 1. for-in dir/subdir to get the filesname
# 2. splitext filename to filter

import os

def getFiles(dir, suffix): # 查詢根目錄,檔案字尾 
    res = []
    for root, directory, files in os.walk(dir):  # =>當前根,根下目錄,目錄下的檔案
        for filename in files:
            name, suf = os.path.splitext(filename) # =>檔名,檔案字尾
if suf == suffix: res.append(os.path.join(root, filename)) # =>吧一串字串組合成路徑 return res for file in getFiles("./", '.py'): # =>查詢以.py結尾的檔案 print(file)