Complementing the another answer, which at the end commented on the following:
However, in this way, the content ends up being stored in memory through the buffer, which can affect the performance of the application according to the size of the file in question.
In fact, this may be a problem. But it’s not just that: when writing to the same file with the option w
, the file is truncated and its contents are lost. And if any error occurs while writing, the file will get corrupted.
A solution would be to first write the new content in a temporary file, and only at the end, if all went well, rename this temporary file to the original:
import shutil, tempfile
# lê do arquivo e escreve em outro arquivo temporário
with open('data.txt', 'r') as arquivo, \
tempfile.NamedTemporaryFile('w', delete=False) as out:
for index, linha in enumerate(arquivo, start=1):
if index == 2: # linha 2, mudar o conteúdo
out.write('Novo conteúdo\n')
else: # não é linha 2, escreve a linha sem modificação
out.write(linha)
# move o arquivo temporário para o original
shutil.move(out.name, 'data.txt')
So, if any problem occurs while writing, only the temporary file will get corrupted (but as it is temporary, it is not so problematic), and the original will be intact.
To get the line number, I used enumerate
, but like the default is to start counting at zero, I added the parameter start
so it starts at 1 (so the second line will be at index 2 instead of 1).
Has as an example of the original text and the desired?
– Jefferson Quesado
that question is very clear to me.
– jsbueno
Now I understand the question perfectly
– Jefferson Quesado