简体   繁体   中英

Python script need to save output to text file

I have peiced together some code from the internet to capture pressed keys and the current active window title and am trying to write the output of the python script to a text file.

The script works fine in the IDLE console and prints pressed keys and logs any change in the current active window.

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)

I am looking for a simple way to write the outputs i can see in the console to a text file. It is probably very simple but i am very much a beginner. Thanks

Python has a native open() function, no import needed, which allows you to handle files. This function "loads" the file into memory, and can be set into various modes:

  • open("filename.txt", "a") , appending the content to a new line;
  • open("filename.txt", "w") , overwriting the content; and
  • open("filename.txt", "r") , setting it to read-only.
  • open("filename.txt", "x") , to create a file.


You can add a "+" to each of this modes ("a+", "w+"), if you want the file to be created if it doesn't already exist.
You define the file in memory to a variable as such: a = open("filename.txt", "w") , and can then text = a.read() to load the content of the file to a string, or a.readlines() to load the strings into an array, split per \\n .
Use a.write("Your desired output") to save the content to the file, if the file is in write or append modus.

Edit:

Try to only open files for as long as they are actually needed.

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

in order to avoid blocking other parts of your program, and avoid corrupting your files if Python crashes unexpectedly.

Just add

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

a option is for appending to a file and + means that if the file is not there just create one with the specified name.

EDIT:

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

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

try this when run program in console

python your_script.py > path_to_output_file/outpot.txt

in case '>' not work then try '>>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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