Skip to main content
 首页 » 编程设计

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

2025年05月04日23kerrycode

我从互联网上收集了一些代码来捕获按下的键和当前事件的窗口标题,并试图将 python 脚本的输出写入文本文件。

该脚本在 IDLE 控制台中运行良好,并打印按下的键并记录当前事件窗口中的任何更改。

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 拆分。
如果文件处于写入或附加模式,请使用 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 意外崩溃时损坏文件。