使用re:import re
filenames = [
'file1.jpg',
'file2.jpg',
'file3.jpg',
'file4.jpg',
'fileA.jpg',
]
### We'll match on a general pattern of any character before a number + '.jpg'
### Then, we'll look for a file with that number in its name and return the result
### Note: We're grouping the number with parenthesis, so we have to extract that with each iteration.
### We also skip over non-matching results with teh conditional 'if'
### Since a list is returned, we can unpack that by calling index zero.
max_file = [file for file in filenames if max([re.match(r'.*(\d+)\.jpg', i).group(1) for i in filenames if re.match(r'.*(\d+)\.jpg', i)]) in file][0]
print(f'The file with the maximum number is: {max_file}')
输出:
The file with the maximum number is: file4.jpg
注意:无论文件名中的数字前是否有字母,这都是有效的,因此您可以(几乎)随意命名文件。在
*第二个解决方案:使用创建日期。*
这与第一个类似,但我们将使用操作系统模块并迭代目录,返回一个具有最新创建日期的文件:
^{pr2}$