以下是代码实现,该代码假设两个文件的大小不会超出内存限制,如果文件过大,可以考虑一行一行地读取比较,或者使用文件流逐行读取比较:

def compare(file1, file2):
    with open(file1, 'r') as f1, open(file2, 'r') as f2:
        if f1.read() == f2.read():
            return True
        else:
            return False

file1 = input('请输入第一个文件名:')
file2 = input('请输入第二个文件名:')

if compare(file1, file2):
    print('No difference!')
else:
    print('difference!')

运行效果如下:

请输入第一个文件名:file1.txt
请输入第二个文件名:file2.txt
No difference!
Python 函数比较两个文本文件内容是否相同

原文地址: https://www.cveoy.top/t/topic/nOsI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录