python-使用os.walk查找文件名中具有最高值的文件

问题描述

我有一些文件夹,每个文件夹中都有一个文件列表,如下所示:

file-Test01-summary.xlsm

file-Test02-summary.xlsm

file-Test03-summary.xlsm

文件数量可以不同!在每个文件夹中可以是 3 到 5 个文件! 我需要一个代码来查找测试编号最高的文件

如果代码可以用 os.walk()

编写会很棒

解决方法

尝试获取文件名并将其拆分如下以过滤整数。

我没有在 os.walk() 中编写代码,但我希望这能帮助您开始。

#List with all file names
from os import walk

FilenameList = ['file-Test01-summary.xlsm','file-Test02-summary.xlsm','file-Test03-summary.xlsm']

for (<dirpath>,<dirnames>,<filenames>) in walk (<mypath>):
    FilenameList.extend(filenames)
    break

#This list will contain all the test numbers
IntegerList = []

#This loop will go through all filenames and filter the testnumbers and appand them to Integerlist
for file in FilenameList:
      for item in File:
        try:
            IntegerList.append(float(t))
        except ValueError:
          pass

#This will print the highest test number
print(max(IntegerList))

希望这有帮助;)

,

一种简单的方法是迭代所需的文件,而不是使用 sorted 对列表进行升序或降序排序。

使用 ofunctions.file_utils 可以方便地仅列出带有 .xlsm 扩展名的文件。 安装包使用:

python -m pip install ofunctions.file_utils`

这是工作代码:

import ofunctions.file_utils

files = ofunctions.file_utils.get_files_recursive('.',ext_include_list='.xlsm')
files = sorted(files,reverse=True) # Remove reverse=True to achieve ASC ordering
print(files)

结果:

['.\\file-Test03-summary.xlsm','.\\file-Test02-summary.xlsm','.\\file-Test01-summary.xlsm']

那么您的最高数字将是 files[0]

您可以将参数 depth=1 添加到 get_files_recursive 以防止下降到子目录中。

免责声明:我是 ofunctions 的作者