I want to create Gif file with many Png files. The problem is the Png files has date within their names e.g. (name_2017100706_var.png). The dates start are in yymmddhh format and start at 2017100706 end at 2017101712, with increment of 6 hrs, so the next file name will contain 2017100712 in its name, and I want the code to loop over the files sequentially according to the dates. So I am using the following code:
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
Example using a class object
with the following built-in functions:
os.listdir(path='.')
sorted(iterable, *, key=None, reverse=False)
object.__iter__(self)
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)
Tested with Python: 3.4.2