Python脚本需要将输出保存到文本fi

2024-04-18 19:51:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我从互联网上收集了一些代码来捕捉按下的键和当前活动窗口的标题,并试图将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)

我正在寻找一种简单的方法来将我在控制台中看到的输出写入文本文件。这可能很简单,但我是个初学者。谢谢


Tags: keyfromimport脚本newdatetimeiftime
3条回答

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")将内容保存到文件中。在

编辑:

尽量只打开文件,只要它们是实际需要的。在

with open("filename.txt", "r") as f:
    file_contents = f.read()
    # file_contents = "This file contains\nvery important information"

    file_lines = f.readlines()
    # file_lines = ["This file contains", "very important information"]
    # Similar to file_lines = file_contents.split("\n")

为了避免阻塞程序的其他部分,并避免在Python意外崩溃时损坏文件。在

在控制台中运行程序时,请尝试此操作

python your_script.py > path_to_output_file/outpot.txt

如果'>;'不起作用,则尝试'>>'

只要加上

with open('textfile.txt', 'a+') as f:
  f.write(ff)

a选项用于附加到文件,+表示如果文件不在那里,只需创建一个具有指定名称的文件。在

编辑:

^{pr2}$

编辑2:

def on_press(key):
    print ('{0} pressed'.format(key))
    k = key + '\n'
    with open('textfile.txt', 'a+') as f:
      f.write(key) 

# and in get_titles()
ff= (moment2 + " : " +  "Moved T0 : "+ new_title + '\n')
with open('textfile.txt', 'a+') as f:
      f.write(ff)

相关问题 更多 >