2

I'm writing a backup script that runs through a folder structure and copies any files that have been changed since the last run through. I can detect modifications and creations through the files' properties (using getmtime and getctime) but I also need to be able to detect if a file has been moved. Is there a simple way of doing this without having to record the whole file structure and comparing on each update?

Note that this will only be used on a Windows system.

EDIT: If possible I'd like to avoid using external libraries.

2
  • Did you know that when a file is moved (renamed), its ctime is updated? But if you rely on this for differential backup, beware that if a directory is renamed, the ctimes of the files in it aren't updated. Commented Feb 18, 2015 at 14:54
  • When a file is copied and pasted to somewhere else its ctime is changed. If it's dragged somewhere else in explorer its ctime does not change. This is what I'm trying to detect. Commented Feb 18, 2015 at 15:01

1 Answer 1

3

You can run a daemon that monitors the parent folder for any changes, by using, E.G., the watchdog library:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
4
  • Thanks. I'd come across watchdog before but I'm trying to figure out if I can do this without using external libraries. Forgot to mention that in the question, sorry >.> Commented Feb 18, 2015 at 15:33
  • Consider what you're asking -- "is it possible to determine whether something has happened without recording it or observing it in real-time?" :)
    – Mark R.
    Commented Feb 18, 2015 at 15:52
  • I guess you could say my question is whether there's something that does record it that I can access in a similar way to checking the time created or modified. Commented Feb 18, 2015 at 15:56
  • @MarkR. - Can you please let me know if I can customize the message. I have to capture the user as well as IP address of the machine while logging. Commented Jun 10, 2021 at 8:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.