1

Im trying to iterate over files but want to the newer file get iterated first.

import os

directory = os.getcwd() + "\\Images"
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    if filename.endswith(".png") or filename.endswith(".jpg"):
       #blablabla

This code works fine but it iterates sorted by file name instead of creation time. How can this be done?

Yosua Sofyan
  • 307
  • 1
  • 4
  • 11
  • 1
    Does this answer your question? [How to get file creation & modification date/times in Python?](https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python) – gold_cy Mar 13 '20 at 11:56

2 Answers2

2

You can use "glob" like this:

import glob
import os

os.chdir("/Images")
files = glob.glob("./*")
files.sort(key=os.path.getmtime)
for file in files:
    filename = os.fsdecode(file)
    if filename.endswith(".png") or filename.endswith(".jpg"):
            #blablabla

Or you can use lambda expression like this:

import os

directory = os.getcwd()+ "\\Images"
files = os.listdir(directory)
files.sort(key=lambda x: os.stat(os.path.join(directory, x)).st_mtime)

for file in files:
    filename = os.fsdecode(file)
    if filename.endswith(".png") or filename.endswith(".jpg"):
            #blablabla

By the way st_mtimeused to sort by modification time, you can use st_ctime for creation time

0

Using os.path.getmtime(path) (Reference: https://docs.python.org/3/library/os.path.html#os.path.getmtime)

You can make a dictionary which stores the time as the key and the file path as the value, like so:

files = {}
for file in os.listdir(directory):
    time_created = os.path.getmtime(file)
    files[time_created] = file

Then to sort them you can just do this:

files = dict(sorted(files.items()))
damaredayo
  • 1,048
  • 6
  • 19