在Python2.4中尝试比较使用“with open…”打开的文件会产生语法错误

2024-05-28 22:53:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何比较Python2.4.4中的两个文件?文件的长度可能不同。你知道吗

我们的服务器上有python2.4.4。我想使用difflib.unified_diff()函数,但找不到适用于python2.4.4的示例。你知道吗

我在Stack Overflow上看到的所有版本都包含以下内容:

with open("filename1","r+") as f1:
  with open ("filename2","r+") as f2:
    difflib.unified_diff(..........)

我遇到的问题是在版本2.4.4中,with open ...生成了一个语法错误。我想远离使用系统调用diff或sdiff是可能的。你知道吗


Tags: 文件函数版本服务器示例stackaswith
1条回答
网友
1楼 · 发布于 2024-05-28 22:53:54

with语句是introduced in Python 2.5。不过,不用它就可以直接做你想做的事情:

a.txt文件

This is file 'a'.

Some lines are common,
some lines are unique,
I want a pony,
but my poetry is awful.

b.txt文件

This is file 'b'.

Some lines are common,
I want a pony,
a nice one with a swishy tail,
but my poetry is awful.

Python

import sys

from difflib import unified_diff

a = 'a.txt'
b = 'b.txt'

a_list = open(a).readlines()
b_list = open(b).readlines()

for line in unified_diff(a_list, b_list, fromfile=a, tofile=b):
    sys.stdout.write(line)

输出

 - a.txt 
+++ b.txt 
@@ -1,6 +1,6 @@
-This is file 'a'.
+This is file 'b'.

Some lines are common,
-some lines are unique,
I want a pony,
+a nice one with a swishy tail,
but my poetry is awful.

相关问题 更多 >

    热门问题