Read lines until a particular line occurs

June 13, 2017, at 06:39 AM

I have two test files. File1 - A number of titles, File 2 - Titles and the description. I need to read one line from File 1 , ie a title and find the matching title in File 2 and print the description until a line 'END' I tried using islice and but does not work

with open('H:/Python/proj1/p4 faults.swi', 'r') as content_file:
    content = content_file.readlines()
    for x in ViolList:
         for i, line in enumerate(content):
            line =line.upper()
            x1 = x1.upper()
            if x1 in line :
                count = count + 1
                if line.strip()== 'End':
Answer 1

Your code has a few problems including referring to a variable x1 that hasn't been defined, and defining count and i variables that aren't used. Trying to get won't work, because you already read all the content when you called content_file.readlines().

Instead do something like this: iterate through the content; if a line contains a title then set a flag and write the line to the output file; the flag will be True, and the loop will keep writing lines, until it encounters 'end'.

with open('titles', 'r') as titles_file:
    titles = [title.strip().upper() for title in titles_file]
description = False
with open('H:/Python/proj1/p4 faults.swi', 'r') as content, open('outfile.txt') as output:
    for line in content:
        if description:
            if line.strip().upper() == "END":
                 description = False
        elif line.strip().upper() in titles:
            description = True
Rent Charter Buses Company
help¡¡¡¡ help¡¡¡¡ [on hold]

help¡¡¡¡ help¡¡¡¡ [on hold]

I need to make a program that Select a combination between elements and chemical symbol and element name, each in a combobox and a check button to say whether they are consistent or not

What does the '[notebook]' in 'pip install ipython[notebook]' mean?

What does the '[notebook]' in 'pip install ipython[notebook]' mean?

The '[notebook]' appears to be some kind of modifier, but as I was installing Jupyter rather than ipython I suddenly wondered what other variants of this modifier I've been missing out on, perhaps something that would install specific kernels or configurations...