The easiest way for you to do this, in my view, is to create a buffer
temporary to store the contents of the final file, replacing the line that
you want to change. The logic is simple: open the file in read mode,
lines, and if the line is desired, write in the buffer the new one.
content, otherwise write the content of the line itself. At end,
replace the contents of the file with buffer contents.
from io import StringIO
buffer = StringIO()
with open('data.txt', 'r') as stream:
for index, line in enumerate(stream):
# index == 1 representa a segunda linha do arquivo:
buffer.write('Novo conteúdo da linha\n' if index == 1 else line)
with open('data.txt', 'w') as stream:
stream.write(buffer.getvalue())
See working at Repl.it
However, in this way, the content ends up being stored all in memory through
buffer , which can affect application performance depending on the size of the
file in question.