【问题标题】:How to skip new lines for comparison in python?如何在python中跳过新行进行比较?
【发布时间】:2020-01-08 12:51:42
【问题描述】:

我有一个 python 代码,它比较 2 个文本文件并显示它们是否有差异。首先我对文件进行排序,然后在排序后删除它们在文本末尾的空格,然后进行比较。

#!/usr/bin/env python

import difflib
from pathlib import Path

path1=Path('/data1/Dir/thesaurus/file1')
path2=Path('/data1/Dir/thesaurus/file2')

text1 = open(str(path1)).readlines()
text1.sort(key=lambda x: x.strip('#').rsplit('.', 1)[0])
text2 = open(str(path2)).readlines()
text2.sort(key=lambda x: x.strip('#').rsplit('.', 1)[0])

for line in difflib.unified_diff(text1, text2, n=0):
print line,

实际上那些用于比较的文件是不同服务器的/etc/passwd。这段代码运行良好,但最近我发现由于\n,它没有为某些服务器返回正确的输出。我如何在比较中消除这些\n

例如file1和file2有这样的内容:

@=> cat file1
wise:x:wuser:/home/wise:/sbin/nologin
nafs:x:user:/home/nafs:/sbin/nologin
khor:x:khor:/home/khor:/bin/bash
jari:x:user:/home/jari:/sbin/nologin
test:x:Test:/home/test:/sbin/nologin
zabbix:x:Zabbix Agent:/home/zabbix:/usr/sbin/nologin
@=> cat file2
wise:x:wuser:/home/wise:/sbin/nologin
nafs:x:user:/home/nafs:/sbin/nologin
jari:x:user:/home/jari:/sbin/nologin
zabbix:x:Zabbix Agent:/home/zabbix:/usr/sbin/nologin

我的期望:

---
+++
@@ -6 +5,0 @@
-khor:x:khor:/home/khor:/bin/bash
@@ -8 +7 @@
-test:x:Test:/home/test:/sbin/nologin  

我得到了什么:

---
+++
@@ -1 +1 @@
-nafs:x:user:/home/nafs:/sbin/nologin
+nafs:x:user:/home/nafs:/sbin/nologin
@@ -6 +5,0 @@
-khor:x:khor:/home/khor:/bin/bash
@@ -8 +7 @@
-jari:x:user:/home/jari:/sbin/nologin
+jari:x:user:/home/jari:/sbin/nologin
@@ -12 +10,0 @@
-test:x:Test:/home/test:/sbin/nologin

我在没有比较部分的情况下运行了我的代码并打印了text1text2 来查找问题,我看到在它们在一个文件中而不是在其他文件中错误返回的行旁边有一个\n文件。

【问题讨论】:

    标签: python linux sorting difference passwd


    【解决方案1】:

    Strip 每一行?

    text1 = [l.strip() for l in open(str(path1))]
    

    【讨论】:

    • 我认为最后需要]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多