Python代码,用于从/ directory开始查找所有目录/子目录中新创建,修改和删除的文件

时间:2011-11-10 23:10:19

标签: python

我知道如何列出目录树中的所有子目录和文件。但我正在寻找方法列出所有新创建的文件,修改和(如果可能)从根目录开始的目录树中所有目录中删除的文件。

3 个答案:

答案 0 :(得分:15)

您可以通过查看每个文件的“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 :(得分:1)

看看“man find”

创建一个比较的临时文件

示例:

  

find / -type f -newerB tempFile

男人的某些部分找到

-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

答案 2 :(得分:1)

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