0

I have a file named item.dat containing bracketed keywords:

[ITEM1]
banana
peach
apple
orange
grapes
[END]
[ITEM3]
tennis
bowling
[END]
........

I want to the lines between the bracketed keywords to be processed. The variable wil contain the bracketed lines I want to extract. The problem is how do I perform a line comparison for "[ItemName]"?

del item[:]
ItemName = "ITEM3"
with open('item.dat') as input_data:
    for line in input_data:
        if line.strip() == "\[ItemName\]":   # the problematic line
            break
    for line in input_data:  # This keeps reading the file
        if line.strip() == '[END]':
            break
        print line
        item.append(line)
et_phonehome
  • 137
  • 12
  • The variable ItemName will be my search string. In this case, ItemName is set to ITEM3. Next time, I may set it to say ITEM100. – et_phonehome Jul 18 '15 at 03:42

3 Answers3

1

Try this regex:

^\[(?!END).*]

Regex live here.

Explaining:

^\[          # starts with a '[' character
(?!END)      # don't match 'END'
.*]$         # take all till the end ']' character

Hope it helps.

0

I believe that the question that you have asked can be answered using the solution provided here with only slight modifications. As the linked answer is so thorough, I will not repeat the answer, but if for some reason that does not work, let me know and I can provide some alternatives.

Community
  • 1
  • 1
bern
  • 366
  • 1
  • 10
0

Don't know if I really understand the question, but a simple way of extracting the bracketed values is this:

items = []
variables = []

with open('item.dat') as input_data:
    for line in input_data:
        line = line.strip()
        if line and line[0] == '[' and line[-1] == ']':
            variables.append(line)
        else:
            items.append(line)

Printing the two lists using the data provided results in:

variables = ['[ITEM1]', '[END]', '[ITEM3]', '[END]']
items = ['banana', 'peach', 'apple', 'orange', 'grapes', 'tennis', 'bowling']
Plenka
  • 1,099
  • 7
  • 17