Is there any way to override a specific line of a text file using Python?

2

I would like to edit a specific line in a file, but file.write () does not allow this type of manipulation.

Being the Text:

1 "Ola"
2 "Como vai?"
3 "Tudo bem?"

I would like to edit only line 2:

1 "Ola"
2 "Boa tarde"
3 "Tudo bem?"

In python we can read a specific line using file.readline () , but I did not find a function that would allow you to edit a specific line. Is there a function for this?

    
asked by anonymous 22.11.2017 / 04:57

1 answer

3

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.

    
23.11.2017 / 17:26