如何遍历名称中包含日期的文件

How to loop over files that has date in their names

我想创建包含许多 Png 文件的 Gif 文件。问题是 Png 文件的名称中有日期,例如(name_2017100706_var.png)。日期开始采用 yymmddhh 格式,从 2017100706 开始,到 2017101712 结束,增量为 6 小时,因此下一个文件名将在其名称中包含 2017100712,我希望代码根据日期顺序循环文件。所以我使用以下代码:

import os
import imageio
import datetime
png_dir = '/home/path/'
images = []
counter = 2017100706
while counter <= 2017101712:
    for file_name in os.listdir(png_dir):
        if file_name.startswith('name_'+str(counter)):
            file_path = os.path.join(png_dir, file_name)
            images.append(imageio.imread(file_path))
            counter +=6
imageio.mimsave('/home/path/movie.gif', images, duration = 1)

Question: How to loop over files that has date in their names

使用具有以下 内置函数 class object 示例:


import os
import imageio

class SortedDateListdir():
    def __init__(self, dpath):
        # Save directory path for later use
        self.dpath = dpath

        listdir = []

        # Filter from os.listdir only filename ending with '.png'
        for fname in os.listdir(dpath):
            if fname.lower().endswith('.png'):
                listdir.append(fname)

        # Sort the list 'listdir' according the date in the filename                
        self.listdir = sorted(listdir, key=lambda fname: fname.split('_')[1])

    def __iter__(self):
        # Loop the 'self.listdir' and yield the filepath
        for fname in self.listdir:
            yield os.path.join(self.dpath, fname)

if __name__ == "__main__":
    png_dir = '/home/path'
    movie = os.path.join(png_dir, 'movie.gif')

    images = []
    for fpath in SortedDateListdir(png_dir):
        images.append(imageio.imread(fpath))

    imageio.mimsave(movie, images, duration=1)

使用 Python 测试:3.4.2