I want to write into a text file from the second line.
At the moment to write data onto a text file I use:
with open("data1.txt", "w") as file:
    file.write(str(round(strength, 2)) + "\n")
file.close()
'Strength' as in a value(Number)
To read from a specific line (The second line in this case) from the text file:
with open("data1.txt", "r", encoding="utf-8") as file:
    S1 = file.readlines()
    S1 = float(S1[1].strip())
file.close()
How can I write onto a file from the second line starting with:
with open("data1.txt", "w+", encoding="utf-8") as file:
I know that to write from the beginning of the text file I need to use:
file.seek(0)
How can I replace/change/write from the second line?
You need to read the file first:
with open("file.txt", "r") as file:
    lines = file.readlines()
Then change the second line:
lines[1] = str(round(strength, 2)) + "\n"
Then write everything back:
with open("file.txt", "w") as file:
    for line in lines:
        file.write(line)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With