简体   繁体   中英

python nested loop using loops and files

I have a nested for loop that doesn't seem to be working. The inner loops variable is not updating as the outer loop is executing.

for line in file:
    record = line.split(',')
    id = record[0]
    mas_list.append(id)
    for lin in another_file:
        rec = lin.split(',')
        idd = rec[3]
        if idd == id:
        mas_list.append("some data")
        mas_list.append("some data")

now this works for an id of 001 but when I get to id 002 the outer loop keeps track of that but for some reason the inner loop and only the first item is appended to the list

You are iterating the file object with

for lin in another_file:

After the first iteration of the outer loop, the another_file is exhausted. So, the inner loop never executes after the first outer loop iteration.

If you want to do it like this, you need to open the file again like this

with open("another.txt") as another_file:
    for lin in another_file:
        ...

Even better, you can gather only the necessary information before the outer loop itself and use the preprocessed data like this

# Create a set of ids from another file
with open("another.txt") as another_file:
    ids = {lin.split(',')[3] for lin in another_file}

with open("mainfile.txt") as file:
    for line in file:
        record_id = line.split(',')[0]
        mas_list.append(record_id)
        # Check if the record_id is in the set of ids from another file
        if record_id in ids:
            mas_list.append("some data")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM