1

I have:

master = open('master.txt', 'r')
transaction = open('transaction.txt', 'r')

master_list = []
employee_list = []


    for line in master:
        # split the line
        record = line.split(',')
        # extract id from record
        emp_id = record[0]
        # add id to list
        employee_list.append(emp_id)

        for li in transaction:
            # split the line
            rec = li.split(',')
            i_d = rec[3]
            print(i_d)

This works as expected and outputs

001
001
001
001
001
002
002
002
002
002
003
003
003
003
003
004
004
004
004
004
005
005
005
005
005

but if I use an if statement in the nested loop like this:

for li in transaction_file:
            # split the line
            rec = li.split(',')
            i_d = rec[3]
            if i_d == emp_id:
                print(emp_id)

I only get 001 001 001 001 001

why is that?

1
  • @akonsu are you trolling, bro? Commented Jul 5, 2014 at 20:47

1 Answer 1

2

You never rewind your transaction file; you go through it once during the first cycle of your master loop.

The structure you have may not be the best possible, but:

for line in master:
    # split the line
    record = line.split(',')
    # extract id from record
    emp_id = record[0]
    # add id to list
    employee_list.append(emp_id)

    transaction.seek(0)
    for li in transaction:
        # split the line
        rec = li.split(',')
        i_d = rec[3]
        print(i_d)

The transaction.seek(0) will rewind you back to the beginning of the file (move the reading position to the start of the file) every time before you iterate through it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.