简体   繁体   中英

Writing the first 10 numbers in a txt file and then updating with the new values ( python )

Im very new to python, and im trying to plot a graph. I have a print () which prints the output of my battery voltage to a txt file called "output.txt.

Python Script

 f = open("C:\Scripts\output.txt", "w")

   print("{0:.1f} V".format(voltage/10.0),file=f) #battery voltage

  f.close()

Now the values just keeps updating in the first line of the txt file everytime the script is run. And i know its happening because i use the "w".

Is there a way that i can write the first 10 values and then start updating the 11 value from the top by deleting the rest of the old values. Any help is appreciated. Thanks a lot for your time!!

Since requesting to edit a file means you are asking the os for permission to read/write to the file, then in general for such a small number of values, it would be easiest to simply rewrite all of them at once. For example,

def update_file(values):
    with open("C:\Scripts\output.txt", "w") as f:
        for v in values:
            f.write("{0:.1f} V".format(v/10.0))

values = [0]*10
update_file(values)
new_voltage = 11.0
values.pop(0)
values.append(new_voltage)
update_file(values)

Read the file, throw away the first value, add yours and overwrite the file.

Just a thought, it might be easier to just store the data in a list while you are collecting it and then only write the last 10 data points when you are done collecting data.

Here is an example:

import time

def write_data(file_name, data):
    with open(file_name, 'w') as f:
        for voltage in data:
            f.write("{0:.1f} V".format(voltage/10.0))
            f.write('\n')

if __name__ == "__main__":
    FILE = "C:\Scripts\output.txt"
    N = 10 # maximum number of lines
    data = [0] * N
    for i in range(50): # 50 or however many data points you want to gather
        voltage = 10.15 # Some function that get's the current voltage
        data[i%N] = voltage # 15 % 10 = 5 so we just write over the 6th line when writing the 16th data point.
        time.sleep(1) # however many seconds you want between data points
    
    # Then once you're finished collecting data, go ahead and write it permanently once.
    write_data(FILE, data)

You will still have access to the data in the list data while it is being collected. But here you only need to write to "output.txt" once.

So data will look like:

[v0, v1, v2, v3, v4, v5, v6, v7, v8, v9] # after the first 10 points have been received
[v10, v11, v12, v3, v4, v5, v6, v7, v8, v9] # after the first 13 points have been received

Then you can write the data once you're done collecting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM