Skip to main content
 首页 » 编程设计

python之是否可以检测文件是否已在 Python 中移动

2024年10月25日10artech

我正在编写一个备份脚本,它运行整个文件夹结构并复制自上次运行以来已更改的所有文件。我可以通过文件的属性(使用 getmtime 和 getctime)检测修改和创建,但我还需要能够检测文件是否已被移动。有没有一种简单的方法可以做到这一点,而不必记录整个文件结构并在每次更新时进行比较?

请注意,这仅适用于 Windows 系统。

编辑:如果可能的话,我想避免使用外部库。

请您参考如下方法:

您可以运行一个守护程序来监视父文件夹的任何更改,例如,使用 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()