在Python中比较两个文件

3
我有如下代码。我查看了其他stackoverflow链接,但它们比我的稍微复杂一些。
目前我的文本文件有hello(在file1中)和hell(在file2中)作为数据。
我相信我的逻辑是正确的,但我得到以下错误。
TypeError: object of type '_io.TextIOWrapper' has no len()

我哪里做错了?

def compareString(line1,line2): #sub function to compare strings of files
    i=0 #initial index
    while line1[i]==line2[i]: #compare each line until they are equal
        i=i+1
    if line1[i]!=line2[i]: #if unequal
        print('Mismatch at character ',i,line1[i]) #print error message

def compareMain(): #
    file1=input('Enter the name of the first file: ') #input file1 name
    file2=input('Enter the name of the second file: ') #input file2 name

    fp1=open(file1,'r') #open file1, reading mode
    fp2=open(file2,'r') #open file2, reading mode
    for line1 in range(len(fp1)): #Getting each line of file1
        for line2 in range(len(fp2)): #Getting each line of file2
            compareString(line1,line2) #Call compare function
    fp1.close() #Close file1
    fp2.close() #Close file2

compareMain() #Execute
4个回答

1
我会这样做:

def compare_files():
    file1=input('Enter the name of the first file: ') #input file1 name
    file2=input('Enter the name of the second file: ') #input file2 name
    fp1=open(file1,'r') #open file1, reading mode
    fp2=open(file2,'r') #open file2, reading mode
    if (fp1.read() == fp2.read()):
        print("Files are the same")
    else:
        print("Files are not the same")

compare_files()

方法.read()将会返回文件的内容。我们获取这两个文件的内容,然后比较它们的内容。

0

你不需要使用 range(len(fp1))。你可以直接使用 fp1。这样应该可以解决错误。

def compareString(line1,line2): #sub function to compare strings of files
    i=0 #initial index
    while line1[i]==line2[i]: #compare each line until they are equal
        i=i+1
    if line1[i]!=line2[i]: #if unequal
        print('Mismatch at character ',i,line1[i]) #print error message

def compareMain(): #
    file1=input('Enter the name of the first file: ') #input file1 name
    file2=input('Enter the name of the second file: ') #input file2 name

    fp1=open(file1,'r') #open file1, reading mode
    fp2=open(file2,'r') #open file2, reading mode
    for line1 in fp1: #Getting each line of file1
        for line2 in fp2: #Getting each line of file2
            compareString(line1,line2) #Call compare function
    fp1.close() #Close file1
    fp2.close() #Close file2

compareMain() #Execute

1
做到了。感谢您的快速回复。 - Jeff Benister
1
为什么不使用.read()呢?这将给您整个文件的内容。您可以将此内容与第二个文件的内容进行比较。您也可以使用.read()获取第二个文件的内容。 - golobitch
@golobich 我也会尝试这种方法。我对Python和编程整体还很新。 - Jeff Benister
你可以考虑使用difflib(https://docs.python.org/2/library/difflib.html)进行文件比较,因为你现在的方法可能会显示所有行都不同,如果一个文件缺少第一行并且其余所有行与另一个文件相同。difflib用法的代码示例在https://dev59.com/bmIk5IYBdhLWcg3wl_TE中。如果你只想知道文件内容是否相同,比较校验和是有效的,filecmp(https://docs.python.org/2/library/filecmp.html)也是如此。 - user4322779

0
正如Tris所提到的,我建议使用difflibhttps://docs.python.org/2/library/difflib.html)。以下是您可以使用的片段:
import difflib
import sys

file1=sys.argv[1] 
file2=sys.argv[2]

line1 = open(file1).readlines()
line2 = open(file2).readlines()

line1_idx = 0
line2_idx = 0

for l1 in line1:
    l1 = l1.rstrip()
    line2_idx = 0
    for l2 in line2:
        l2 = l2.rstrip()
        diff = difflib.SequenceMatcher(None, l1, l2)
        for tag, i1, i2, j1, j2 in diff.get_opcodes():
            if((tag == "delete") or (tag == "replace") or (tag == "insert")):
                print("Mismatch file1-line%d file2-line%d, line1-index[%d:%d] line2-index[%d:%d]" % (line1_idx, line2_idx, i1, i2, j1, j2))
        line2_idx += 1
    line1_idx += 1

0

在我开始回答这个问题之前,我意识到问问题的人想要一个差异,而不仅仅是一个相同与否的检查。但我觉得可能会有些人希望得到这样的答案,所以我还是提供了这个解答。

虽然main()函数只适用于两个文件,但核心代码可以处理任意数量的文件。无论哪种方式,它都只会检查到第一个不匹配的行。

#
# Python 2/3 compatibility
#

from __future__ import print_function

try:
    from itertools import izip as zip  # Python 2
except ImportError:
    pass  # Python 3

try:
    input = raw_input  # Python 2
except NameError:
    pass  # Python 3


#
# You can leave out everything above if you're on Python 3
#

def all_equal(first_item, *items):
    return all(item == first_item for item in items)


def iterables_are_identical(*iterables):
    return all(all_equal(*tup) for tup in zip(*iterables))


def files_are_identical(*files, **kwargs):
    mode = kwargs.get('mode', 'r')

    open_files = []
    try:
        for f in files:
            open_files.append(open(f, mode))

        return iterables_are_identical(*open_files)
    finally:
        for handle in open_files:
            handle.close()


def main():
    msg = 'Enter the name of the %s file: '
    file_a = input(msg % 'first')
    file_b = input(msg % 'second')

    if files_are_identical(file_a, file_b):
        print('Files are identical')
    else:
        print('Files are NOT identical')


if __name__ == '__main__':
    main()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接