Compare Two Files And Write To A New File But Only Output A Few Lines?
I want to compare two txt files with all lines,but when i run the code it response only a few results,the loop is not effective run,It seems missed a lot of lines in File1,only a
Solution 1:
You should re-open File2
in inner loop or use file.seek
to jump to the start of the file because after the first iteration the file pointer is at the end of File2
.
Help on file.seek
:
>>> print file.seek.__doc__
seek(offset[, whence]) -> None. Move tonew file position.
Argument offsetis a byte count. Optional argument whence defaults to0 (offsetfromstartof file, offset should be >=0); other valuesare1
(move relative tocurrent position, positive or negative), and2 (move
relative toendof file, usually negative,....
Solution 2:
Thanks to the answers above.And with my special appreciation to Nisan.H and Ashwini Chaudhary,I've solved the problem by your help,add only a line before "for line2 in File2"~~~
def compareLines(filename1,filename2):
File1=open(filename1,'r')
File2=open(filename2,'r')
File3=open("Result.txt",'w')
finalList=[]
for line1 in File1:
File2.seek(0)
for line2 in File2:
set1=set(line1.split(" "))
set2=set(line2.split(" "))
print line1
print line2
similarNumber=len(set1.intersection(set2))/float(len(set1.union(set2)))
File3.write('Simmilar rate:'+str(similarNumber)+' '+str(len(set1.intersection(set2)))+" words in incoindence\n")
finalList.append(similarNumber)
File1.close()
File2.close()
File3.close()
os.remove(filename1)
os.remove(filename2)
return finalList
Post a Comment for "Compare Two Files And Write To A New File But Only Output A Few Lines?"