python中的文件计数器或最后5个文件

2024-03-29 10:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到一个5个最近导入的图片列表到一个文件夹,以饲料到一个功能加载到一个联系人名单他们。你知道吗

我有一个程序带来的文件,它使用一个计数器来命名它们00001,00002等。。。我在想

while blah:
N = '0000'x
x = x+1

但当你超过10的时候,它就崩溃了,因为现在是00010。你知道吗

我觉得我应该能弄明白,但我完全无法理解。你知道吗

另一方面,如果我能让程序将X个最新文件加载到函数中,那也会很好。你知道吗

图像名称通过此公式运行。你知道吗

 imgs = [Image.open(fn).resize((photow,photoh)) for fn in fnames]

所以我认为它们的格式应该是('00001.jpg','00002.jpg','00003.jpg'…)

谢谢你的帮助。你知道吗


Tags: 文件程序功能文件夹列表计数器图片联系人
2条回答
>>> '{:05}'.format(10)
00010

对于基于此编号的文件排序:

import os

# List all files in current directory
files = os.listdir('.')
recent_images = sorted(files)[-5:]

on the other hand, if I could just have the program load the X newest files into the function, that would also work great.

可以使用^{}sorted获取最近更改的文件列表:

>>> import os
>>> sorted(filenames, key=lambda x:os.path.getmtime(x), reverse=True)[:5]

相关:How to get file creation & modification date/times in Python?

相关问题 更多 >