0

This is what I have

file=open(test, 'w')
file.write(GetWindowText(GetForegroundWindow()))

And what I want is to make it write the current window to the txt file every 5 seconds.

Xyzzel
  • 115
  • 2
  • 10

2 Answers2

2

For that you need to loop it. The following code should help you.

Updated

Also make the file name to be a string or it will give an AttributeError

import time
filename = "test"
file = open(filename, 'wa') # w+ is to append new lines to the file
while True:
    file.write(GetWindowText(GetForegroundWindow()))
    time.sleep(5)
Jaysheel Utekar
  • 1,171
  • 1
  • 19
  • 37
  • 1
    it should be `a+` if you want to append new lines , `w+` **Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.** For further reading https://stackoverflow.com/a/23566951/8150371 – Stack Jan 14 '18 at 19:19
0

You could use time.sleep() if you want to pause for a certain number of seconds.

import time
print("something")
time.sleep(5)    # pauses for 5 seconds
print("something")

If you place this in a loop it would print approximately* every 5 seconds. (Not exactly, since your program still needs to execute the other lines in your loop in the meantime. But maybe this is good enough for your purposes.)

If you need it exactly every 5 seconds you can use library schedule. Install with pip install schedule. See https://stackoverflow.com/a/41647114/9216538 for an example.