Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

One way you could do this is by reading the first line using file.readline(), counting the number of characters in the first line using len(file.readline()) then using file.seek(len(file.readline()) + 1) to begin writing from that position, i.e. the next line.

You may need to alter the +1, I haven't tested this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top