zoukankan      html  css  js  c++  java
  • 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'Dd{8}D',s)
    print(res_1)
    View Code
  • 相关阅读:
    python运行错误---TabError: Inconsistent use of tabs and spaces in indentation
    python运行错误------Non-UTF-8 code
    opencv错误(Unhandled expection at at 0x0007EEE...)
    fatal error LNK1112: 模块计算机类型“X86”与目标计算机类型“x64”冲突——我的解决方案
    基础术语
    opencv
    图像归一化
    人脸相关数据库
    堆排序
    abp学习(二)
  • 原文地址:https://www.cnblogs.com/nmucomputer/p/12002924.html
Copyright © 2011-2022 走看看