在Python中使用difflib比较两个.txt文件 [英] Comparing two .txt files using difflib in Python

查看:156
本文介绍了在Python中使用difflib比较两个.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个文本文件,并在比较文件中输出不匹配的第一个字符串,但是由于我对python很陌生而遇到了困难.谁能给我一个使用此模块的示例方法.

I am trying to compare two text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module.

当我尝试类似的操作时:

When I try something like:

result = difflib.SequenceMatcher(None, testFile, comparisonFile)

我收到一个错误消息,说文件"类型的对象没有len.

I get an error saying object of type 'file' has no len.

推荐答案

对于初学者,您需要将字符串传递给difflib.SequenceMatcher,而不是文件:

For starters, you need to pass strings to difflib.SequenceMatcher, not files:

# Like so
difflib.SequenceMatcher(None, str1, str2)

# Or just read the files in
difflib.SequenceMatcher(None, file1.read(), file2.read())

那将解决您的错误.要获取第一个不匹配的字符串,我将带您进入 difflib文档的美好世界./a>

That'll fix your error anyway. To get the first non-matching string, I'll direct you to the wonderful world of difflib documentation.

这篇关于在Python中使用difflib比较两个.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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