seek - Python: How to 'write' on the second line of a text file ignoring the first line -
i wanna know code/s can 'write' in text file second line.
atm write data on text file:
with open("data1.txt", "w") file: file.write(str(round(strength, 2)) + "\n") file.close()
'strength' in value(number)
to 'read' specific line (the second line in case) text file:
with open("data1.txt", "r", encoding="utf-8") file: s1 = file.readlines() s1 = float(s1[1].strip()) file.close()
so how can 'write in file second line starting with:
with open("data1.txt", "w+", encoding="utf-8") file:
i know .. 'write' beginning of text file need use:
file.seek(0)
so how can replace/change/write second line?
many thanks
you need read file first:
with open("file.txt", "r") file: lines = file.readlines()
then change second line:
lines[1] = str(round(strength, 2)) + "\n"
then write back:
with open("file.txt", "w") file: line in lines: file.write(line)
Comments
Post a Comment