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.
For that you need to loop it. The following code should help you.
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)
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.