python - 使用 python 3.5 按行比较两个文件,将每行差异输出到新文件中的新行

标签 python python-3.x compare

此类问题已被问过多次,但我似乎无法找到完全相同的场景并使用 python 3。(在我的例子中为 3.5)

我有两个文件 txt 或 csv。我需要比较每一行并将差异输出到新文件中的新行。

这是我到目前为止所尝试过的:这很接近,但我无法弄清楚如何使每一行成为一个新行,我似乎只能使每个单词成为一个新行或一行上的所有内容。

a = open('test1.txt').read().split()
b = open('test2.txt').read().split()
c = [x for x in b if x not in a]
open('test3.txt', 'wt').write('\n'.join(c)+'\n')

.join 之前的\n 使每个单词成为一个新行,我不希望每个差异成为一个新行,我想要同一行上一行的所有差异。 我希望这是有道理的。

示例: 测试1.txt:

how are you
I am well
all is good

test2.txt:

how are you
I like toys
all is not well

输出: 测试3.txt

am well
good

我也尝试过这段 CSV 代码:但我不能出错。

import csv

f1 = open ("test1.csv")
oldFile1 = csv.reader(f1)
oldList1 = []
for row in oldFile1:
    oldList1.append(row)

f2 = open ("test2.csv")
oldFile2 = csv.reader(f2)
oldList2 = []
for row in oldFile2:
    oldList2.append(row)

f1.close()
f2.close()

print [row for row in oldList1 if row not in oldList2]

我收到此错误:我认为这与我使用的是 3.5 版本有关,而此代码是为 2.7 版本编写的?

File "test3.py", line 18
    print [row for row in oldList1 if row not in oldList2]
                 ^
SyntaxError: Missing parentheses in call to 'print'

感谢您的帮助

最佳答案

您的第一个代码的问题是您正在拆分整个文件,这将按空格(不仅仅是换行符)拆分您的文件。

您只需压缩分割线并将单词放在一起即可:

with open('test1.txt') as f1, open('test2.txt') as f2, open('result.txt', 'w') as f3:
    for line1, line2 in zip(f1, f2):
        sp1 = line1.split()
        sp2 = line2.split()
        f3.write(' '.join([i for i in sp1 if i not in sp2]) + '\n')

关于python - 使用 python 3.5 按行比较两个文件,将每行差异输出到新文件中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37302708/

相关文章:

compare - VHDL 无符号向量与整数比较

ios - if(NSOrderedAscending == result) 有人能解释一下吗

python - 比较序列 Python

python - iPython 3 使用 Python 2 而不是 Python 3

Python Uvicorn——获取SSL证书信息

python子进程popen将主目录设置为cwd

python将项目添加到列表并在获得空值时停止

python - apache Airflow 调度程序未调度作业

python - 如何绘制随机平面

python - 在 Django 中,保存到数据库时如何返回现有模型实例