'New file creation detection using Python in Windows
Is there a possibility to detect if a new file is created on Windows using Python programming language?
Maybe my questions sounds meaningless, but I need this information to develop a program that can detect if a new file is created on my computer by a given application (maybe a virus, or any other benign application).
Solution 1:[1]
A script to check all files on your specified folder/drive and check for changes to the names or new files added.
import os
import pickle
from multiprocessing import Process
def scanner(root_dir, output):
temp = set()
#if not os.path.isfile(output): # if output does not exist create it
with open(output, 'a'):
pass
files = os.walk(root_dir) # go through all dirs and sub dirs
for root, dirs, f in files:
if f:
temp.update(f) # add all "f" files to the set
with open(output, 'rb') as data:
if os.path.getsize(output) > 0: # if the file has data, it is not the first run so load and compare
b = pickle.load(data)
print " Deleted files {}".format(b-temp) # if a file name has been changed been deleted
print "Amended or New files {}".format(temp-b) # if a file name has been changed or one added
with open(output, 'wb') as data: # write current files and save to output
pickle.dump(temp, data)
if __name__ == '__main__':
# start process for each drive
p1 = Process(target=scanner, args=("/path1", "data.pickle"))
p1.start()
p2 = Process(target=scanner, args=("/path2", "data1.pickle"))
p2.start()
Solution 2:[2]
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import subprocess as sp
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
print(event.event_type, event.src_path)
def on_created(self, event):
print("on_created", event.src_path)
print(event.src_path.strip())
if((event.src_path).strip() == ".\test.xml"):
print("Execute your logic here!")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
while True:
try:
pass
except KeyboardInterrupt:
observer.stop()
- pip install watchdog
- Create a scheduled task for this script in the Task scheduler and monitor the folder where the file will be created.
Solution 3:[3]
you would have to have/create a database of all files on the computer and scan through every possible name (go through all ASCII values for a char then ad add or increment the next char to a reasonable length) to see if it is there using this you could use the compare the old database and new database to see the changes
Edit: this could help Browse files and subfolders in Python (search in the C or default drive for everything and save its location)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Padraic Cunningham |
Solution 2 | user3349907 |
Solution 3 | Community |