在python中每隔5秒写一次file.write

时间:2018-01-14 19:10:32

标签: python

这就是我所拥有的

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

我想要的是让它每隔5秒将当前窗口写入txt文件。

2 个答案:

答案 0 :(得分:2)

为此你需要循环它。以下代码可以帮助您。

更新

还要将文件名设为字符串,否则将提供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)

答案 1 :(得分:0)

如果您想暂停一定的秒数,可以使用time.sleep()

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

如果将其置于循环中,它将每5秒打印一次*。 (不完全是,因为你的程序在此期间仍然需要执行循环中的其他行。但是这可能对你的目的来说已经足够了。)

如果您每5秒钟就需要它,您可以使用图书馆时间表。使用pip install schedule安装。有关示例,请参阅https://stackoverflow.com/a/41647114/9216538