Hello how do I make it so I the file still writes whilst also closing / saving the file? This is my code:
from time import time, sleep
import os
ip = '8.8.4.4'
results_file = open(r"results.txt", "a")
while True:
sleep(3 - time() % 3)
response = os.popen(f"ping {ip} -n 1").read()
if "Received = 1" and "Approximate" in response:
print((str(now)) + f": UP {ip} Ping Successful")
results_file.write((str(now)) + f"UP {ip} Ping Successful" + "\n")
results_file.close()
else:
print((str(now)) + f": Down {ip} Ping Unsuccessful")
results_file.write((str(now)) + f"Down {ip} Ping Unsuccessful" + "\n")
results_file.close()
The thing is, I need it to constantly log every 60 seconds, (currently on 3 so its quicker) but when it does it once, it instantly stops because it's closed.
Error message:
Traceback (most recent call last):
File "C:/Users/huibd/Desktop/Project/pythonProject3/app/app2.py", line 20, in <module>
results_file.write((str(now)) + f"UP {ip} Ping Successful" + "\n")
ValueError: I/O operation on closed file.
I hope someone can help me, I've been trying out stuff for about an hour now.