[英]Most recent file from a directory with Python
import os
fish=os.listdir("H:\Comu\Solo")
print(fish)
The result is: ['lamba_20081104.pdf', 'conal_20070918.pdf', 'apialas_20220628.pdf']
结果是:
['lamba_20081104.pdf', 'conal_20070918.pdf', 'apialas_20220628.pdf']
the result is a list of the three file in the directory and my wished final result is: 20220628结果是目录中三个文件的列表,我希望的最终结果是:20220628
I am not able to proceed...我无法继续...
The characters of the file to be taken are from -12 to -4取文件的字符为-12到-4
The result represents the date of the younger file (28.06.2022) in the directory "H:\Comu\Solo", because the number are date!结果表示目录“H:\Comu\Solo”中较年轻文件(28.06.2022)的日期,因为数字是日期! In contrast with Ruby - Get the second most recent file from a directory?
与Ruby 相比 - 从目录中获取第二个最近的文件? , in my case is the name-code of the file that suggests me the date!
,在我的情况下是建议我日期的文件的名称代码!
Someone can write the script to obtain 20220628?有人可以写脚本来获取20220628吗?
thank you very much非常感谢您
Try this in one line:在一行中尝试:
max(fish, key=lambda x: x.split("_")[1].split(".")[0])
Python max accepts an argument( key
) that will return your custom max function. Python max 接受一个参数(
key
),它将返回您的自定义 max 函数。
as @sniperd said,you can also use regex in the key
:正如@sniperd 所说,您还可以在
key
中使用正则表达式:
max(l, key=lambda x: re.findall(r"\d+", x))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.