-1

I have a large text file. I want to delete a range of some unwanted lines inside the file. But I want to keep the lines before and after this range. Can anyone suggest me something?

  • 3
    There is no [tag:python] in this question. See [ask], how to create a [mcve], and [edit](https://stackoverflow.com/posts/72461563/edit) the question. – Peter Wood Jun 01 '22 at 12:04
  • 1
    See [**`fileinput`**](https://docs.python.org/3/library/fileinput.html#fileinput.input) with the `inplace` parameter. [**`enumerate`**](https://docs.python.org/3/library/functions.html#enumerate) the line numbers and check whether they are in [**`range`**](https://docs.python.org/3/library/functions.html#func-range). – Peter Wood Jun 01 '22 at 12:08
  • 2
    In general I think it's probably better to ask more specific questions. This reads a bit like you're wanting us to do your homework at school. Try figuring it out, then when you get stuck with something specific, ask a more narrow question. – Ken Kinder Jun 01 '22 at 12:09
  • 1
    If you know which lines you want to delete and their span, you can just parse your text file with a counter variable and add each line to a list or to another text file. Once your counter reaches the begining of unwanted lines, you just skip them and you only write back to the file or list once your counter reaches the end of your unwanted lines. – Maxime Bouhadana Jun 01 '22 at 12:10
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jun 01 '22 at 12:14
  • Does this answer your question? [Python program to delete a specific line in a text file (duplicate)](https://stackoverflow.com/q/48829584/6045800) – Tomerikoo Jun 01 '22 at 12:34

3 Answers3

0

You can use text = textFile.readlines() which will convert the file into a list with have each line as an entry in that list. Then you can loop through each line and see whether it is the one you want to delete. The use text.remove(i) to delete that line from the list. i is the line in the loop with the text that you want to remove.

Overture
  • 75
  • 1
  • 10
0

You can try this:

range_ = 10, 20 # Range you want to delete (inclusive)

with open('file.txt', 'r+') as f:
    lines = f.readlines()
    f.seek(0)
    f.truncate()
    f.writelines(lines[:range_[0] - 1] + lines[range_[1]:])
965311532
  • 245
  • 2
  • 11
0

I think the easiest way to start this would be to write output to a new file (that way if you have a bug you don't destroy your original file)

Try this:

to_delete = range(5, 15)

with open("in_file.txt", "r") as in_file:
    with open("out_file.txt", "w") as out_file:
        for i, line in enumerate(in_file):
            if i not in to_delete:
                out_file.write(line)

If that succeeded you can then replace the original with the new file:

import shutil

shutil.move("out_file.txt", "in_file.txt")
Anentropic
  • 28,868
  • 10
  • 92
  • 135