Reputation: 386
I am reading two different files with for loop. First "for loop" stops after first iteration. The print output is only line1 of f1 with all lines of f2 but then exit the loop.
for line1 in f1:
line1 = line1.split('\t')
for line2 in f2:
line2 = line2.split('\t')
print line1,line2
f1:
x1
x2
x3
f2:
y1
y2
y3
output:
x1 y1
x1 y2
x1 y3
x2 y1
x2 y2
x2 y3
x3 y1
x3 y2
x3 y3
Upvotes: 0
Views: 5982
Reputation: 352
Your loops are currently nested, which means that your program will read the entire contents of f2 for every line in f1. but once the end of file 2 is reached (at the end of the first outer look there are no more lines in f2 to read. so we manually reset the cursor to the beginning.
Attempt 4: You were not resetting the cursor on file 2 once you got to the end of the file the first time round, unless you reopen the file in each iteration you must move the cursor to the beginning manually. If I have now understood you correctly:
def print_both(f1, f2):
f1.seek(0)
f2.seek(0)
for line1 in f1:
line1 = line1.split('\t')
for line2 in f2:
line2 = line2.split('\t')
print(line1, line2)
f2.seek(0)
print_both(open("f1.tsv", 'r'), open("f2.tsv", 'r'))
Upvotes: 1