Search code examples
pythonfilelimittruncate

Writing and overwriting to a file with a limit of 10 lines


Currently I have my code setup where it will only write a maximum of 10 lines in a text file using the counter variable. Once I start the program again, I erase the contents of the text file in the beginning with truncate, and then it writes new values for 10 lines.

Instead of clearing the file in the beginning, I want to overwrite the previous lines starting from the top, while keeping the maximum 10 line limit. How can I go about doing this? Basically how can I overwrite data with a 10 line limit, without having to clear it with truncate. (So I can keep some old data)

print("Clearing all Previously stored pH Data")
f = open('PHAverage.txt', 'r+')
f.truncate(0)

counter=0

while True: #Polling Sensor Data
    pH=Sensor Value
    if counter<10:
        fb = open('PHAverage.txt','a+')
        fb.read
        fb.seek(0)
        fb.write(PH + "\n")
        fb.close()
    counter += 1

EDIT**

Based on the feedback so far, to provide an example, I want to start overwriting data at the start of the file, every 10 polls (or 10 counters). Can something like this work,

if counter%10== 0

    fb = open('PHAverage.txt','a+')
    fb.seek(0)
    fb.write(PH + "\n")
    fb.close()
    f.truncate()

counter += 1


Solution

  • Your only talking about 10 lines, it's probably easiest to just read the whole file, change an entry and write it all back out. Like this function that updates the pH at the line pointed to by index:

    def savePH(filename, index, ph):
        with open(filename, 'r+') as f:
            data = list(f)
            data[index] = f"{ph}\n"
            f.seek(0)
            f.writelines(data)
            f.truncate()
    

    This assumes you already have a file with 10 lines of pH data, and there isn't any error checking.

    counter = 0
    while True:
        pH = sensor_value
        savePH('PHAverage.txt', counter, ph)
        counter = (counter + 1) % 10