How to load only one line and modify it

1

I want to modify only one line of a file, something like this

    with open('arquivo.txt', 'r+') as f:

    for line in f.readlines():
        if line == algumacoisa:
            line.write('textoaqui');
            break
    f.close()

I saw in another question that to do this you should load the whole file, modify it, and save again, however this is not feasible, because the file has millions of lines, and I do not want to save all the millions of lines every time you run the function.

    
asked by anonymous 10.02.2018 / 18:28

1 answer

1

Using the following it is possible to read the file by lines. Once a line is read, the old one is discarded by the garbage collector:

import os
with open('arquivo.txt', 'r+') as f:
    for linha in f:
        with open('arquivo-1.txt', 'a+') as f:
            if line == algumacoisa:
                f.write('textoaqui')

            else:
                f.write(linha)

            f.write('\n')

os.remove('arquivo.txt')
os.rename('arquivo-1.txt', 'arquivo.txt')
    
11.02.2018 / 15:18