【问题标题】:Python code to find all newly created, modified and deleted files in all the directories/sub-directories starting from / directoryPython代码查找从/目录开始的所有目录/子目录中所有新创建、修改和删除的文件
【发布时间】:2011-11-10 23:10:19
【问题描述】:

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

【问题讨论】:

  • 请指定新创建的内容适合您。最后一小时内?最后一天?一年以来?如果您知道如何构建目录树,为什么不直接使用os.lstat 访问文件属性?
  • 然后使用st=os.lstat(filepath)st.st_mtime 字段并检查与当前时间的差异是否小于1800 - 就是这样。

标签: python


【解决方案1】:

您可以通过查看每个文件的“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

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

【讨论】:

  • 运行上面的代码,出现以下错误: 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: str.format 在 Python2.6 中引入。对于早期版本,您可以使用%s 样式的字符串格式。我将编辑我的帖子以说明我的意思。
【解决方案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")

【讨论】:

  • 我构建它是为了查看一个目录并在最后一段时间内选择修改过的文件,然后替换这些文件中的文本。这个脚本没有放置,我不得不从上面的答案中拼凑起来,所以我想其他人可能会来找它。
  • 请使用此信息编辑您的答案。此外,一个完整的答案应该有几行描述它的作用。请阅读以下文章:How do I write a good answer?
【解决方案3】:

看看“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2013-01-07
    相关资源
    最近更新 更多