python - 使用 python 检测新的或修改的文件

标签 python linux file filesystems

<分区>

我正在尝试检测何时在目录中创建新文件或何时修改目录中的现有文件。

我尝试搜索可以执行此操作的脚本(最好是在 python 或 bash 中),但没有找到。我的环境是 linux 和 Python 2.6

Related Question

最佳答案

您可以使用 gio,它是 GLib 的文件系统部分(在 GLib 的 python 绑定(bind)中)

import gio

def directory_changed(monitor, file1, file2, evt_type):
   if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED,
       gio.FILE_MONITOR_EVENT_DELETED)):
       print "Changed:", file1, file2, evt_type

gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)

但是,您的程序必须运行 GLib 主循环才能使事件到达。一种快速测试方法是使用:

import glib
ml = glib.MainLoop()
ml.run()

GLib 是一个高级库,非常适合应用程序。您不必关心它使用哪个底层系统进行文件监控。


我现在看到您使用的是 Fedora Core 2。真的是版本 2 吗?在 GLib 中使用 GIO 可能太旧了。已经提到的 Pyinotify 可能是一个更好的解决方案,尽管不太便携。

关于python - 使用 python 检测新的或修改的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1618853/

相关文章:

当我重定向输出时,Python 程序不会在 docker 容器中的 shell 脚本中运行

python - 仅更新 Django 表单中的 ForeignKey 字段

c - 使用 -std=c99 编译时,struct ip_mreq 消失

c - fseek 在打开的文件指针上失败

c# - 如何检查文件夹中是否存在文件?

python - 将类的属性和确定它的方法分开是否可以/pythonic?

python - 索引错误: index 1 is out of bounds for axis 0 with size 1 while storing the result as a tuple in python

linux - 无法将 ‘const timeval’ 转换为 ‘__time_t {aka long int}’

Linux 出包率

java - XML 文件位于内存中,而不是作为磁盘上的文件