1

I have a text file that looks a bit like this:

line 1
line 2
line 3
line 4

line 1
line 2
line 3
line 4

(etc)

At every line 1 I want to perform a specific operation, and at every line 2 a different operation, etc. The pattern of line repetition (including blanks) holds throughout the document, so currently I just have a counter that resets at every blank line and a bunch of if statements:

if counter == 1:
    this(line)
elif counter == 2:
    that(line)
elif etc

My question, is there a more efficient, more Pythonic way of doing this?

Thanks!

Mike S
  • 1,451
  • 1
  • 16
  • 34
  • Is there always one blank line between paragraphs? – aghast May 06 '17 at 04:38
  • Yes. I just edited my post to reflect this – Mike S May 06 '17 at 04:39
  • There is no `switch` statement in python, but there are ways to achieve the same. If you do not want a bunch of `elif`s have a look at http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python. – JohanL May 06 '17 at 04:43

2 Answers2

4

You could try a lookup on a list of functions:

line_processors = [
    lambda ln: print("line 1 of paragraph:", ln),
    lambda ln: print("line 2 of paragraph:", ln),
    lambda ln: print("line 3 of paragraph:", ln),
    lambda ln: print("line 4 of paragraph:", ln),
    lambda ln: print("blank line:", ln),
]

with open("myfile.txt") as f:
    for i, line in enumerate(f):
        line_processors[i % 5](line)
aghast
  • 14,785
  • 3
  • 24
  • 56
0

You can read all your file lines and create a list of lines. After that you just need to operate with your list indexes.

with open(fname) as f:
    content = f.readlines()    
content = [x.strip() for x in content] 

# this(content[0])
# that(content[1])
Vinícius Figueiredo
  • 6,300
  • 3
  • 25
  • 44