0

I have a massive .txt file, and I want to read it one line at a time, and if I find a line which meets a certain condition, I want to go into that file and change the last n characters of that line only.

The only way I've seen of doing that is to re-write all the lines to a new .txt, while changing the lines you want to change.

This is how I envision my desired logic would look.

for line in infile:
    if 'ABC' in line:
        infile.#here would come the code to replace characters

I don't think with open() has this functionality - or does it? Is there a library which does what I describe?

Thanks!

  • Maybe this can help: https://stackoverflow.com/a/18857381/5478462 – pastaleg Jun 24 '22 at 19:28
  • 1
    This seems like exactly what I want! Just wanted to make sure that 1) UTF-8 encoding is single-byte and 2) that when I create a .txt file via `with open('name.txt', 'x')` in python, it is with UTF-8 encoding. Thanks for the answer, feel a bit bad that I wasn't able to find that thread :D! – Ventsi Radev Jun 24 '22 at 19:34

0 Answers0