Python 遞歸讀取文件夾內所有文件名(包含子文件夾)


需要對學生交作業數量進行統計,因為班級和多次作業,文件夾層次和數量很多,需要統計學生的文件數量。

第一步必須讀取所有文件名,分析發現這是一個典型的遞歸過程

  1. 進入文件夾
  2. 生成文件列表
  3. 循環所有列表
  4. 如果是文件就保存文件名到列表中
  5. 如果是文件夾就進入遞歸,將返回結果保存到文件名列表中
  6. 返回生成的列表
 1 import os
 2 
 3 def check_file(file_path):
 4     os.chdir(file_path)
 5     print(os.path.abspath(os.curdir))
 6     all_file = os.listdir()
 7     files = []
 8     for f in all_file:
 9         if os.path.isdir(f):
10             files.extend(check_file(file_path+'\\'+f))
11             os.chdir(file_path)
12         else:
13             files.append(f)
14     return files
15 
16 file_list = check_file("d:\ftp\作業上交")
View Code

其中,要注意的是歸來時要將文件路徑返回回來

第二步是對列表找那個文件名的處理,很簡單!

  1. 產生字符串
  2. 使用正則表達式對學號進行查找
  3. 結果可以導入到EXCEL中處理,或者直接循環生成字典
# Author:Winter Liu
import os
import re
import xlwt

def check_file(file_path):
    os.chdir(file_path)
    print(os.path.abspath(os.curdir))
    all_file = os.listdir()
    files = []
    for f in all_file:
        if os.path.isdir(f):
            files.extend(check_file(file_path+'\\'+f))
            os.chdir(file_path)
        else:
            files.append(f)
    return files

file_list = check_file("C:\迅雷下載")

book = xlwt.Workbook()
sheet = book.add_sheet('文件名')
i = 0
for data in file_list:
    sheet.write(i,0,data)
    i += 1

book.save('文件名搜索.xls')

s = ' '.join(file_list)
res_1 = re.findall(r'\D\d{8}\D',s)
print(res_1)
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM