Skip to content Skip to sidebar Skip to footer

Python Nested For-loop Not Executing Beyond First

This script is meant to read through a file and take in the number (numA) and the text next to it (sourceA). It then uses this and compares it to every other line in the file. If a

Solution 1:

You are trying to read twice from the same file. Files use a current position to determine what to read next, and iterating over the remaining lines in the inner loop, you moved that position all the way to the end.

You could 'fix' that by seeking back to the start of the file with:

sor.seek(0)

However, looping over the whole file for every line in that file is really inefficient. Use a dictionary to track if you have seen the same information on a previous line:

withopen(sortedNums, "r")as sor, \
     open(reusedNums, 'a') as reused:
    seen = {}
    for line in sor:
        ifnot'####'in line:
            continue
        nums, source = line.rstrip().split('####')
        if nums in seen and seen[nums] != source:
            print("Found reused Nums")
            reused.write('{} {} {}\n'.format(nums, source, seen[nums]))
        seen[nums] = source

By storing data in a dictionary, you only have to loop over the file once.

Post a Comment for "Python Nested For-loop Not Executing Beyond First"