import os
import time
import psutil
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self, file_path):
super().__init__()
self.file_path = file_path
def on_modified(self, event):
self.log_event(event)
def on_created(self, event):
self.log_event(event)
def on_deleted(self, event):
self.log_event(event)
def on_moved(self, event):
self.log_event(event)
def log_event(self, event):
# Get the file path of the modified or created file
file_path = os.path.abspath(event.src_path)
# Get the access mode of the file event
if file_path != self.file_path:
return
access_mode = ""
if event.is_directory:
access_mode = "read"
elif event.event_type == "modified" or event.event_type == "created":
access_mode = "write"
elif event.event_type=='read':
access_mode="read"
elif event.event_type == "deleted":
access_mode = "delete"
elif event.event_type == "moved":
access_mode = "move"
# Get the process ID of the current process
current_pid = os.getpid()
# Get the process name of the current process
process_name = psutil.Process(current_pid).name()
# Get the current timestamp
current_time = time.strftime("%Y-%m-%d %H:%M:%S")
# Log the file path, access mode, process ID, and timestamp to a file
with open("file_access.log", "a") as f:
f.write(f"{file_path}, {access_mode}, {current_pid}, {process_name}, {current_time}\n")
print(f"{file_path}, {access_mode}, {current_pid}, {process_name}, {current_time}")
if __name__ == "__main__":
file_path = r"C:\Users\SETS\OneDrive\Desktop\file manag\example.txt"
event_handler = MyHandler(file_path)
observer = Observer()
observer.schedule(event_handler, path=os.path.dirname(file_path), recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
output is coming wrong.
C:\Users\Desktop\file manag\example.txt, write, 19944, python.exe, 2023-04-28 10:32:43
C:\Users\Desktop\file manag\example.txt, write, 19944, python.exe, 2023-04-28 10:32:43
output should come
pid and file name where changes happen not python.exe which is current py file running and its pid