Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code to find all newly created, modified and deleted files in all the directories/sub-directories starting from / directory

Tags:

python

I know how to list all subdirectories and files in a directory tree. But I am looking for way to list all newly created files, modified and (if possible) deleted files in all the directories in a directory tree starting from the root directory.

like image 806
nsh Avatar asked Nov 10 '11 23:11

nsh


1 Answers

You could find all files created or modified in the last half-hour by looking at the "mtime" of each file:

import os
import datetime as dt

now = dt.datetime.now()
ago = now-dt.timedelta(minutes=30)

for root, dirs,files in os.walk('.'):  
    for fname in files:
        path = os.path.join(root, fname)
        st = os.stat(path)    
        mtime = dt.datetime.fromtimestamp(st.st_mtime)
        if mtime > ago:
            print('%s modified %s'%(path, mtime))

To generate a list of deleted files, you'd also have to have a list of files 30 minutes ago.


A more robust alternative is to use a revision control system like git. Making a commit of all the files in the directory is like making a snapshot. Then the command

git status -s

would list all files that have changed since the last commit. This will list files that have been deleted too.

like image 120
unutbu Avatar answered Oct 07 '22 15:10

unutbu