-2

I have a file, for example, "data.txt" with "1234567890" text inside. How can my program delete "678", so that "data.txt" will consist of "1234590"?

In addition, data.txt is a really heavy file. So you can't use pure read() or readlines().

I want to use only python tools, so "shell" is not an option.

Gleb
  • 154
  • 8
  • https://stackoverflow.com/questions/5410757/how-to-delete-from-a-text-file-all-lines-that-contain-a-specific-string does this answer your question? – jimmie_roggers Jul 26 '21 at 12:07
  • Does this answer your question? [How to delete from a text file, all lines that contain a specific string?](https://stackoverflow.com/questions/5410757/how-to-delete-from-a-text-file-all-lines-that-contain-a-specific-string) – jimmie_roggers Jul 26 '21 at 12:08
  • @jimmie_roggers no, it doesn't. I want to edit it only using the python tool. – Gleb Jul 26 '21 at 12:12
  • You can read it in chunks. – David Meu Jul 26 '21 at 12:14
  • Yes, It is possible. However, I want to find a way not to rewrite the whole file. – Gleb Jul 26 '21 at 12:16
  • 3
    What you want amounts to random access, for which textfiles are unsuited. If you delete 3 characters from the file, everything that comes after will have to be shifted 3 positions left. To do that you would have to have it all in memory. If the file is too big to fit in memory then your only option is to read it line by line and write out a modified copy line by line, then delete the original and rename the copy. Look at module `in_place` if you find such housekeeping burdensome: `pip install in-place`. – BoarGules Jul 26 '21 at 12:26

1 Answers1

0

You can do something like following:

with open("Stud.txt", "r") as fin:
    with open("out.txt", "w") as fout:
        for line in fin:
            fout.write(line.replace('678', ''))
marianosimone
  • 3,366
  • 26
  • 32
  • This makes a copy of a file w/ the replacement; the question was to apply the replacement to the original file. – Scott Hunter Jul 26 '21 at 12:12
  • @ScottHunter To be fair, I would similarly have assumed it was okay to create a separate output file, until the OP's later clarification that only came after this answer was posted. – alani Jul 26 '21 at 12:28
  • Original post *specifically* asked how to delete text from a file; any clarifications were about how to accomplish that. – Scott Hunter Jul 26 '21 at 13:21