python统计指定目录中文件个数和文件名_python在一个目录中文件名的数量最多

使用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}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值