【问题标题】:Trying to compare files opened using 'with open...' in Python 2.4 gives a SyntaxError尝试比较在 Python 2.4 中使用“with open...”打开的文件会出现 SyntaxError
【发布时间】:2015-06-15 07:49:06
【问题描述】:

如何在 Python 2.4.4 中比较两个文件?这些文件的长度可能不同。

我们的服务器上有 Python 2.4.4。我想使用 difflib.unified_diff() 函数,但找不到适用于 Python 2.4.4 的示例。

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

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

我遇到的问题是在 2.4.4 版本中,with open ... 会生成一个 SyntaxError。我想远离使用系统调用 diff 或 sdiff 是可能的。

【问题讨论】:

  • 请从 2.4.4 升级。如果您要说“这取决于服务器主机”,请雇用新的服务器主机。如果您要说“我的雇主喜欢这种方式”,请寻找新的工作。
  • 2.4.4 真的很老了……说你可以做到f1,f2 = open("fname1.txt"),open("fname2.txt")

标签: python file with-statement python-2.4 difflib


【解决方案1】:

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.

【讨论】:

  • 工作就像一个魅力。我实际上弄乱了其他 difflib 选项和您提供的格式,发现以下内容提供了更好的输出: for line in context_diff(a_list, b_list, fromfile=a, tofile=b):
猜你喜欢
  • 2011-06-04
  • 2012-03-06
  • 2014-03-11
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多