比较两个文件并写入一个新文件,但只输出几行? [英] Compare two files and write to a new file but only output a few lines?

查看:69
本文介绍了比较两个文件并写入一个新文件,但只输出几行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个txt文件的所有行,但是当我运行代码时,它只响应少数结果,该循环无效运行,似乎在File1中错过了很多行,只出现了第一行File1.

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 appeared the first line of File1.

问题:

我的循环有问题吗?非常感谢!

my loop has any problem?Thanks very much!

def compareLines(filename1,filename2):

    File1=open(filename1,'r')
    File2=open(filename2,'r')
    File3=open("Result.txt",'w')

    finalList=[]
    for line1 in File1:
        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

推荐答案

您应在内部循环中重新打开File2或使用file.seek跳至文件的开头,因为在第一次迭代后,文件指针为在File2的末尾.

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.

关于file.seek的帮助:

>>> print file.seek.__doc__
seek(offset[, whence]) -> None.  Move to new file position.

Argument offset is a byte count.  Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative,....

这篇关于比较两个文件并写入一个新文件,但只输出几行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆