How to load only one line and modify it

Asked

Viewed 83 times

1

I want to modify just one line of a file, something like that

    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 must load the entire 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 I perform the function.

1 answer

1


Using the following it is possible to read the file by lines. As soon as a line is read, the old one is discarded by 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')
  • The only difference to what I want is I don’t intend to write in another file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.