0

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)
Ella
  • 3
  • 4
  • 1
    so, basically, get all the file names that exist in a folder and then sort them by name (sorry, i'm lazy to look for code examples =D). – akhavro Jan 24 '19 at 16:48
  • here is explained how to get files from a folder: https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory And here you can find how to sort a list of strings (filenames): https://stackoverflow.com/questions/36139/how-to-sort-a-list-of-strings – akhavro Jan 24 '19 at 16:53
  • If you can't just list the files in a directory and need to generate the file names, I would suggest using a `datetime` object to store the date time and using a `timedelta` to add 6 hours to each datetime object. This will make it easier to change dates at boundaries. Then you can format the `datetime` object as you want to create the string names you want. – Rachel Jan 24 '19 at 17:03

1 Answers1

0

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

Example using a class object with the following built-in functions:


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

stovfl
  • 14,998
  • 7
  • 24
  • 51