-1

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.

1 Answers1

1

You can flush to ensure data is written without closing. https://www.tutorialspoint.com/python/file_flush.htm#:~:text=Python%20file%20method%20flush(),data%20before%20closing%20any%20file.

results_file.flush()

Note that flush happens automatically on close and if all buffered data is already written, will simply be a noop.

dpwr
  • 2,732
  • 1
  • 23
  • 38