简体   繁体   English

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

[英]python- find the file with the highest value in the file name using os.walk

I have some folders and in each folder is a list of files like below:我有一些文件夹,每个文件夹中都有一个文件列表,如下所示:

file-Test01-summary.xlsm文件-Test01-summary.xlsm

file-Test02-summary.xlsm文件-Test02-summary.xlsm

file-Test03-summary.xlsm文件-Test03-summary.xlsm

the number of files can be different.文件的数量可以不同。 in each folder could be 3 to 5 file!在每个文件夹中可以是 3 到 5 个文件! I need a code to find the file with highest test number.我需要一个代码来查找具有最高测试编号的文件。

It could be great if the code will be write with os.walk()如果代码将使用os.walk()编写,那就太好了

Try to get the name of the file and split it as below to filter the integers.尝试获取文件名并将其拆分如下以过滤整数。

I didn't write the code in os.walk(), but i hope this gives you a start.我没有在 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))

hope this helps;)希望这可以帮助;)

One easy way is to iterate over the required files, than use sorted to sort the list ascendent or descendent.一种简单的方法是遍历所需的文件,而不是使用sorted对列表升序或降序进行排序。

Using ofunctions.file_utils comes in handy to list only files with .xlsm extension.使用ofunctions.file_utils可以方便地仅列出扩展名为.xlsm的文件。 Install the package using:使用以下命令安装 package:

python -m pip install ofunctions.file_utils`

Here's the working code:这是工作代码:

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)

Result:结果:

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

Your highest number will then be files[0] .您的最高数字将是files[0]

You can add parameter depth=1 to get_files_recursive in order to prevent descending into subdirectories.您可以将参数depth=1添加到get_files_recursive以防止下降到子目录。

Disclaimer: I am the author of ofunctions免责声明:我是 ofunctions 的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM