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

9

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


请说明对于您来说,新创建的是什么。在最近一小时内?在过去的一天内?还是自从一年前?如果您知道如何构建目录树,为什么不直接使用os.lstat来访问文件属性呢? - hochl
请使用 st=os.lstat(filepath)st.st_mtime 字段,并检查与当前时间的差是否小于1800。就这样。 - hochl
3个回答

20

您可以通过查看每个文件的“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。将目录中所有文件提交为一个commit就像拍摄一张快照。然后使用以下命令:

git status -s

会列出自上次提交以来发生更改的所有文件,这也会列出已删除的文件。


运行上述代码,会得到以下错误提示:Traceback (most recent call last): File "tsck.py", line 13, in ? print('{p} modified {m}'.format(p=path,m=mtime)) AttributeError: 'str' object has no attribute 'format' - nsh
这个速度太慢了,我们可以找另一种方法,激活系统以记录新创建的文件,然后解析日志文件。或者更好的方法是为新的日志条目添加触发器。这可能会有所帮助! - pylover
@nsh:str.format在Python2.6中引入。对于早期版本,您可以使用%s风格的字符串格式化。我将编辑我的帖子以展示我的意思。 - unutbu

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

我编写了这个程序来查看目录并选择最近一段时间内修改过的文件,然后替换这些文件中的文本。这个脚本不是现成的,我不得不从上面的答案中拼凑起来,所以我想其他人可能也会寻找它。 - Powerboy2
请在您的答案中编辑此信息。此外,完整的答案应该有几行描述它的功能。请阅读以下文章:如何撰写一个好的答案? - Mariano

0

看一下"man find"

创建一个临时文件进行比较

例如:

find / -type f -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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接