Find file in directory with the highest number in the filename

情到浓时终转凉″ 提交于 2019-12-01 11:30:49

I'll try to solve it only using filenames, not dates.

You have to convert to integer before appling criteria or alphanum sort applies to the whole filename

Proof of concept:

import re
list_of_files = ["file1","file100","file4","file7"]

def extract_number(f):
    s = re.findall("\d+$",f)
    return (int(s[0]) if s else -1,f)

print(max(list_of_files,key=extract_number))

result: file100

  • the key function extracts the digits found at the end of the file and converts to integer, and if nothing is found returns -1
  • you don't need to sort to find the max, just pass the key to max directly
  • if 2 files have the same index, use full filename to break tie (which explains the tuple key)

Using the following regular expression you can get the number of each file:

import re

for file in list_of_files:
    num = int(re.search('file(\d*)', file).group(1))  # assuming filename is "filexxx.txt"
    # compare num to previous max, e.g.
    max = num if num > max else max  # set max = 0 before for-loop

At the end of the loop, max will be your highest filename number.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!