bgp*_*ter 11
difflib可以满足您的需求.假设:
A.TXT
this
is
a
bunch
of
lines
Run Code Online (Sandbox Code Playgroud)
b.txt
this
is
a
different
bunch
of
other
lines
Run Code Online (Sandbox Code Playgroud)
像这样的代码:
import difflib
fileA = open("a.txt", "rt").readlines()
fileB = open("b.txt", "rt").readlines()
d = difflib.Differ()
diffs = d.compare(fileA, fileB)
lineNum = 0
for line in diffs:
# split off the code
code = line[:2]
# if the line is in both files or just b, increment the line number.
if code in (" ", "+ "):
lineNum += 1
# if this line is only in b, print the line number and the text on the line
if code == "+ ":
print "%d: %s" % (lineNum, line[2:].strip())
Run Code Online (Sandbox Code Playgroud)
给出如下输出:
bgporter@varese ~/temp:python diffy.py
4: different
7: other
Run Code Online (Sandbox Code Playgroud)
您还需要查看difflib代码"? "并查看您希望如何处理该代码.
(另外,在实际代码中,您希望使用上下文管理器来确保文件被关闭等等)
| 归档时间: |
|
| 查看次数: |
1802 次 |
| 最近记录: |