Reputation: 499
I want to using python to open two files at the same time, read one line from each of them then do some operations. Then read the next line from each of then and do some operation,then the next next line...I want to know how can I do this. It seems that for
loop cannot do this job.
Upvotes: 0
Views: 52
Reputation: 2946
You can try the following code:
fin1 = open('file1')
fin2 = open('file2')
content1 = fin1.readlines()
content2 = fin2.readlines()
length = len(content1)
for i in range(length):
line1, line2 = content1[i].rstrip('\n'),content2[i].rstrip('\n')
# do something
fin1.close()
fin2.close()
Upvotes: 0
Reputation: 113930
file1 = open("some_file")
file2 = open("other_file")
for some_line,other_line in zip(file1,file2):
#do something silly
file1.close()
file2.close()
note that itertools.izip
may be prefered if you dont want to store the whole file in memory ...
also note that this will finish when the end of either file is reached...
Upvotes: 4
Reputation: 30
you can put inside a loop like that:
for x in range(0, n):
read onde line
read the other line
try it
Upvotes: 0
Reputation: 49
Why not read each file into a list each element in the list holds 1 line.
Once you have both files loaded to your lists you can work line by line (index by index) through your list doing whatever comparisons/operations you require.
Upvotes: 0