1

I am trying to create an IOT weather station where in a Python file it would receive data from a temperature sensor and save it in a CSV along with the second(s) it was received.

Since this is going to be plotted in a graph in real time, I can't have it save new data without clearing the CSV file out first since if I did, the line in the graph will overlap, because of the eventual repetition of seconds in the CSV file.

This is a sample of what is saved in the CSV file:

Celcius,Time
56,20.50
57,20.50
58,20.50
59,20.50
00,20.50

I want the code to clear the CSV file once the seconds reach 60 (or 00), so it can be repopulated with new data.

This is what I have come up with so far:

with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if (secondsNow[2] == "00"):
        print("CLEAR CLEAR CLEAR")
        csv_file.close()
    else:
        csv_writer.writerow(info)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    Yes: https://stackoverflow.com/questions/35678391/python-how-do-i-clear-a-txt-file-with-the-open-function – mkrieger1 Feb 08 '22 at 12:33
  • Does this answer your question? [How do I clear a .txt file with the open() function?](https://stackoverflow.com/questions/35678391/how-do-i-clear-a-txt-file-with-the-open-function) – Zach Young Feb 08 '22 at 18:00

3 Answers3

1

You're opening the CSV file in append mode during the minute to add data to the end, what you could then do is close and re-open it in write mode at the end of the minute to start with a fresh file:

while True:
    info = {
        "Time": secondsNow[2],
        "Celcius": secondsNow[2]
    }
    if secondsNow[2] == '00':
        # open in write mode to start again with a blank file
        with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'w') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            csv_writer.writerow(info)
    else:
        # open in append mode to add data to the end
        with open('D:\\WORKSTUFF\\Coding\\ADET\\txt files\\testing.csv', 'a') as csv_file:
            csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            csv_writer.writerow(info)
PangolinPaws
  • 670
  • 4
  • 10
-1

When you open a csv file in python and write something into, it automatically overwrites what was already written in the file.

Daniyal Ishfaq
  • 247
  • 1
  • 7
  • 2
    it depends, you can open the file in append mode, like in the question –  Feb 08 '22 at 12:40
-1

You can clear the file by passing the shell command via python os module:

import os

...
print(CLEAR CLEAR CLEAR)
exit_code = os.system(": > $FILEPATH")
...
Max Skoryk
  • 404
  • 2
  • 10