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

猜你喜欢

转载自www.cnblogs.com/nmucomputer/p/12002924.html