Search code examples
pythonlinuxfilepyinotify

Using pyinotify to watch for file creation, but waiting for it to be completely written to disk


I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it, even before it's completely written to disk.

Is there a way to make pyinotify wait until a file is completely written to disk before notifying me that it's been created? Or is there any easy way to, after I'm notified, make python wait to move it until it's done being written?


Solution

  • Have pyinotify react to IN_CLOSE_WRITE events:

    wm.add_watch(watched_dir, pyinotify.IN_CLOSE_WRITE, proc_fun=MyProcessEvent())
    

    This is from man 5 incrontab, but it applies equally well to pyinotify:

       IN_ACCESS           File was accessed (read) (*)
       IN_ATTRIB           Metadata changed (permissions, timestamps, extended attributes, etc.) (*)
       IN_CLOSE_WRITE      File opened for writing was closed (*)
       IN_CLOSE_NOWRITE    File not opened for writing was closed (*)
       IN_CREATE           File/directory created in watched directory (*)
       IN_DELETE           File/directory deleted from watched directory (*)
       IN_DELETE_SELF           Watched file/directory was itself deleted
       IN_MODIFY           File was modified (*)
       IN_MOVE_SELF        Watched file/directory was itself moved
       IN_MOVED_FROM       File moved out of watched directory (*)
       IN_MOVED_TO         File moved into watched directory (*)
       IN_OPEN             File was opened (*)