Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python to filter files on disk

Tags:

python

I am using below to remove files from disk.

    def match_files(dir, pattern):
       for dirname, subdirs, files in os.walk(dir):
          for f in files:
             if f.endswith(pattern):
                yield os.path.join(dirname, f)

    # Remove all files in the current dir matching *.txt
    for f in match_files(dn, '.txt'):
       os.remove(f)

What I would to remove files from disk that "was not updated today." List the files from today. Check against to update list.

like image 383
Merlin Avatar asked Apr 08 '26 16:04

Merlin


2 Answers

Besides os.stat you could use os.path.getmtime or os.path.getctime, the pro's / con's of which are discussed on this question. You can use datetime.datetime.fromtimestamp to convert the timestamp returned into a datetime object, and then you can do whatever you want. In this example I'll remove files not modified today, create a list of remaining files:

from datetime import datetime, timedelta

today = datetime.now().date()
remaining = []
for f in match_files(dn, '.txt'):
   mtime = datetime.fromtimestamp(os.path.getmtime(f)).date()
   if mtime != today:
       os.remove(f)
   else:
       remaining.append(f)
like image 106
zeekay Avatar answered Apr 11 '26 04:04

zeekay


What is "pattern" ?

Otherwise, the "os.stat" gives the date of the file. Here a sample with the "last mod" date.

    stats = os.stat(file)
    lastmod_date = time.localtime(stats[8])
like image 30
Louis Avatar answered Apr 11 '26 05:04

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!