0

I have a file where only specific "chunks" of lines are needed to be modified, in this case I want to retrieve lines between a and b including those lines as well:

1 
2 a
3 
4 b
5
6
7 a
8
9
10 b

Now i have a list of tuples which indicates in between which line indexes I need to modify the content: [(2, 4), (7, 10)].

Now I need to replace the content of those lines, so something like

with open("file.txt") as file1:
    for index, line in enumerate(log, start=1):
        if index in range(**OF ONE OF THE TUPLES IN THE LIST**):
            line = ....

I don't understand how to achieve this without having nested loops and duplicating stuff/opening the file multiple times.

Thoughts?

tortillla
  • 31
  • 3
  • What do you want to replace the line ranges with? – ASGM Nov 22 '19 at 13:05
  • the issue is that the lines between a and b have wrong information, so i would replace the 'wrong' string with the correct version. – tortillla Nov 22 '19 at 13:09
  • Sure, but where are you getting the "correct" version from? Are you replacing the lines according to some function? – ASGM Nov 22 '19 at 13:10
  • 1
    Possible duplicate of [Python: efficiently check if integer is within \*many\* ranges](https://stackoverflow.com/questions/6053974/python-efficiently-check-if-integer-is-within-many-ranges) – Georgy Nov 22 '19 at 13:14
  • @Geogry Not a duplicate, this question is about the approach for tuples. The answer you linked is for 1. a single integer and 2. not a range check. Bonus points, I came from Google search results to find this better approach in the answer below. – Testerhood Mar 28 '22 at 19:01

1 Answers1

0

Here is a possible solution:

ranges = [(2, 4), (7, 10)]
for line_index in range(number_of_lines):
    if any(line_index in range(start, end + 1) for start, end in ranges):
        # TODO
        # Replace line with something
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50