我从互联网上收集了一些代码来捕捉按下的键和当前活动窗口的标题,并试图将python脚本的输出写入文本文件。在
该脚本在空闲控制台中工作正常,可以打印按键并记录当前活动窗口中的任何更改。在
from pynput.keyboard import Key, Listener
import time
from win32gui import GetWindowText, GetForegroundWindow
import datetime
from threading import Thread
def on_press(key):
print ('{0} pressed'.format(key))
def on_release(key):
('{0} release'.format(key))
if key == Key.esc:
return False
def get_titles():
current_title = None
while True:
moment2 = datetime.datetime.now().strftime("%d-%b-%Y [ %H:%M:%S ]")
new_title = GetWindowText(GetForegroundWindow())
if new_title != current_title:
if len(new_title) > 0:
#logging.info(" Moved to : " + new_title)
current_title = new_title
time.sleep(0.1)
#print(new_title)
ff= (moment2 + " : " + "Moved T0 : "+ new_title)
print (ff)
我正在寻找一种简单的方法来将我在控制台中看到的输出写入文本文件。这可能很简单,但我是个初学者。谢谢
Python有一个本机的
open()
函数,不需要导入,它允许您处理文件。此功能将文件“加载”到内存中,并可设置为各种模式:open("filename.txt", "a")
,将内容追加到新行open("filename.txt", "w")
,覆盖内容;以及open("filename.txt", "r")
,将其设置为只读。在open("filename.txt", "x")
,创建一个文件。在如果您希望在文件不存在的情况下创建该文件,您可以在每种模式(“a+”、“w+”)中添加一个“+”。
您可以将内存中的文件定义为如下变量:
a = open("filename.txt", "w")
,然后可以text = a.read()
将文件内容加载到字符串中,或者a.readlines()
将字符串加载到数组中,按\n
拆分。如果文件处于write或append模式,请使用
a.write("Your desired output")
将内容保存到文件中。在编辑:
尽量只打开文件,只要它们是实际需要的。在
为了避免阻塞程序的其他部分,并避免在Python意外崩溃时损坏文件。在
在控制台中运行程序时,请尝试此操作
如果'>;'不起作用,则尝试'>>'
只要加上
a
选项用于附加到文件,+
表示如果文件不在那里,只需创建一个具有指定名称的文件。在编辑:
^{pr2}$编辑2:
相关问题 更多 >
编程相关推荐