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

时间:2018-12-21 12:13:37

标签: python text save output

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

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

3 个答案:

答案 0 :(得分: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划分。
如果文件处于写入或追加方式,请使用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意外崩溃时损坏文件。

答案 1 :(得分:2)

只需添加

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

a选项用于附加到文件,而+表示如果文件不存在,则仅使用指定名称创建一个文件。

编辑:

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

编辑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)

答案 2 :(得分:0)

在控制台中运行程序时

尝试此操作

python your_script.py > path_to_output_file/outpot.txt

如果'>'不起作用,请尝试'>>'