Python-код для поиска всех вновь созданных, измененных и удаленных файлов во всех каталогах / подкаталогах, начиная с / directory - PullRequest
6 голосов
/ 11 ноября 2011

Я знаю, как перечислить все подкаталоги и файлы в дереве каталогов. Но я ищу способ перечислить все вновь созданные файлы, измененные и (если возможно) удаленные файлы во всех каталогах в дереве каталогов, начиная с корневого каталога.

Ответы [ 3 ]

15 голосов
/ 11 ноября 2011

Вы можете найти все файлы, созданные или измененные за последние полчаса, посмотрев «mtime» каждого файла:

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))

Чтобы создать список удаленных файлов, вы также должны иметьиметь список файлов 30 минут назад.


Более надежной альтернативой является использование системы контроля версий, такой как git.Выполнение фиксации всех файлов в каталоге похоже на создание снимка.Тогда команда

git status -s

выведет список всех файлов, которые изменились с момента последнего коммита.В этом списке также будут удалены файлы.

1 голос
/ 30 сентября 2015
from tempfile import mkstemp
import shutil
import os
import datetime as dt
import sys


# gets the time frame we are going to look back and builds a placeholder list to passover the info from our mtime to slay
now=dt.datetime.now()
ago=now-dt.timedelta(minutes=480)
passover=[]

# the '.' is the directory we want to look in leave it to '.' if you want to search the directory the file currently resides in
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:
            passover.append(path)


def slay(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with open(abs_path,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    old_file.close()
    #Remove original file
    os.remove(file_path)
    #Move new file
    try:
        shutil.move(abs_path, file_path)
    except WindowsError:
        pass

#we pass the passover list to the slay command in a for loop in order to do muiltple replaces in those files.
for i in passover:
    slay(i,"String1","String2")
1 голос
/ 11 ноября 2011

Взгляните на "man find"

создайте временный файл для сравнения

пример:

find / -typef -newerB tempFile

некоторая часть man find

-newerXY reference
          Compares  the  timestamp of the current file with reference.  The reference argument is normally the name of a file (and one
          of its timestamps is used for the comparison) but it may also be a string describing an absolute time.  X and Y  are  place‐
          holders for other letters, and these letters select which time belonging to how reference is used for the comparison.

          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...