0

I have a directory containing files named like so:

2018-07-14
2018-07-12
2018-07-17

Right now I am iterating over all those files like so:

from pathlib import Path

def data_generator(my_dir):
    data_path = Path(my_dir)
    for path in data_path.iterdir():
        print(path)

Is there a simple to make sure I iterate on the files in order using their name as key, from oldest to most recent?

Thomas Reynaud
  • 966
  • 3
  • 8
  • 19
  • using ISO date format lets you sort by date using lexicographic string sorting provided your format (and timezone) are consistent – Aaron Mar 07 '19 at 19:18
  • 2
    Possible duplicate of [How do you get a directory listing sorted by creation date in python?](https://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python) – user1251007 Mar 07 '19 at 19:34

1 Answers1

3

You can enclose data_path.iterdir() with a sorted() function.

from pathlib import Path

def data_generator(my_dir):
    data_path = Path(my_dir)
    for path in sorted(data_path.iterdir()):
        print(path)
martineau
  • 119,623
  • 25
  • 170
  • 301
VietHTran
  • 2,233
  • 2
  • 9
  • 16