user16773013
user16773013

Reputation:

How to get all files modified in a certain time window?

I want to get all files modified/created in the last 1 hour with Python. I tried this code but it's only getting the last file which was created:

import glob
import os

list_of_files = glob.glob('c://*')
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

If I created 10 files it shows only last one. How to get all files created in the last 1 hour?

Upvotes: 4

Views: 2890

Answers (2)

Bouliech
Bouliech

Reputation: 84

Here is another solution, shorter, that uses only the os package:

import os
directory = "/path/to/directory"
latest_file = os.popen(f"ls -t {directory}").read().split("\n")[0]

Upvotes: -1

Peter Badida
Peter Badida

Reputation: 12169

You can do basically this:

  • get the list of files
  • get the time for each of them (also check os.path.getmtime() for updates)
  • use datetime module to get a value to compare against (that 1h)
  • compare

For that I've used a dictionary to both store paths and timestamps in a compact format. Then you can sort the dictionary by its values (dict.values()) (which is a float, timestamp) and by that you will get the latest files created within 1 hour that are sorted. (e.g. by sorted(...) function):

import os
import glob
from datetime import datetime, timedelta

hour_files = {
    key: val for key, val in {
        path: os.path.getctime(path)
        for path in glob.glob("./*")
    }.items()
    if datetime.fromtimestamp(val) >= datetime.now() - timedelta(hours=1)
}

Alternatively, without the comprehension:

files = glob.glob("./*")
times = {}
for path in files:
    times[path] = os.path.getctime(path)

hour_files = {}
for key, val in times.items():
    if datetime.fromtimestamp(val) < datetime.now() - timedelta(hours=1):
        continue
    hour_files[key] = val

Or, perhaps your folder is just a mess and you have too many files. In that case, approach it incrementally:

hour_files = {}
for file in glob.glob("./*"):
    timestamp = os.path.getctime(file)
    if datetime.fromtimestamp(timestamp) < datetime.now() - timedelta(hours=1):
        continue
    hour_files[file] = timestamp

Upvotes: 2

Related Questions