For Loop Problem
For loop issue: in1 = open('file_1', 'r') in2 = open('file_2', 'r') outf = open('out_file', 'w') for line in in1: s = line.split('\t') A = s[1][:-1] B = s[0] coun
Solution 1:
You can iterate over a file only once. To start from the beginning again, use
in2.seek(0)
before the inner loop.
Solution 2:
Solution 3:
Once you have read each line from file_2 in the inner loop then in2 is at end-of-file. If you want to read file_2 for each line in file_1 then add:
in2.seek(0)
just before or after the write.
Solution 4:
When working with files, please do this
withopen('out_file', 'w') as outf:
withopen('file_1', 'r') as in1:
for line in in1:
s = line.split('\t')
a = s[1][:-1]
b = s[0]
counter = 0withopen('file_2', 'r') as in2:
for line in in2:
etc.
Using with
assures your files are closed.
Opening a file in the smallest enclosing scope guarantees it can be read all the way through. It's costly to keep reopening the file, but there are a lot of ways to speed up this application.
Also, please use only lowercase
variable names. Reserve Uppercase
for class names.
Post a Comment for "For Loop Problem"