Ethan Caravella
Ethan Caravella

Reputation: 21

My nested if statement seems to be ending my for loop when I want it to continue

I'm trying to create a dictionary by mapping keys which increment to a string of the lines in a file. I need to evaluate if the line has a specific string: "" and then go back to the for loop and continue creating a string for the value in the dictionary.

fin = open('test_text_document.txt')
document_1 = ''
dictionary_1 = {}
dictionary_reference = 0
for line in fin:
    document_1 = document_1 + str(line)
    if '"<NEW DOCUMENT>"\n' in line:
        dictionary_1[dictionary_reference + 1] = document_1
         document_1 = ''

All that will print when I check dictionary_1 though is the first document key to value pair. Is my if statement stopping my for loop?

Upvotes: 2

Views: 55

Answers (2)

Chris Lawlor
Chris Lawlor

Reputation: 48962

Depending on the size of the file, it might be simpler to read it all into memory, and call split to break it up into separate documents:

with open('test_text_document.txt') as infile:
    content = infile.read()
    documents = content.split('"<NEW_DOCUMENT>"')

Note that split will return a list instead of a dict, which is different than your original code but seems to match how you'd like to access the documents anyway. If you do in fact need a dict, you could get one with this:

d = {i:v for i, v in enumerate(documents)}

Upvotes: 0

Carlos
Carlos

Reputation: 1935

You're not incrementing the key value. You're just assigning the value of 1 to your key.

Set up a counter after setting the value to your key and it will work as expected.

dictionary_1[dictionary_reference] = document_1
dictionary_reference = dictionary_reference + 1

Upvotes: 3

Related Questions