如何在python中获取以下输出

如何在python中获取以下输出,python,python-3.x,python-2.7,scripting,devops,Python,Python 3.x,Python 2.7,Scripting,Devops,我试图比较两个文本文件,其中有子网,并能够得到输出。 但是我需要正确格式的输出 我还想在两个列表中添加一个print语句作为匹配项 目前,我得到的输出为: 2.144.0.0/142.176.0.0/12root@vagrant-ubuntu 我的预期产出: Match in both the lists 2.144.0.0/14 2.176.0.0/12 root@vagrant-ubuntu 代码 检查这是否有效。对于以单独的行写入,可以使用\n。如果您只想在两个列表中放置短语匹配项一次

我试图比较两个文本文件,其中有子网,并能够得到输出。 但是我需要正确格式的输出 我还想在两个列表中添加一个print语句作为匹配项

目前,我得到的输出为:

2.144.0.0/142.176.0.0/12root@vagrant-ubuntu
我的预期产出:

Match in both the lists
2.144.0.0/14
2.176.0.0/12
root@vagrant-ubuntu
代码


检查这是否有效。对于以单独的行写入,可以使用\n。如果您只想在两个列表中放置短语匹配项一次,则需要添加一个if语句

test = 0
fileout = open('9output.txt', 'w')
for val1 in lines1:
    for val2 in lines2:
        if val1 == val2:
            if test == 0:
                fileout.write("Match in both the lists")
                fileout.write(val1+"\n")
                test = 1
            else:
                fileout.write(val1+"\n")
fileout.close()
if test == 0:
    print("No matches found!")

我已经修复了你的压痕。然而,如果没有输入文件,这里发生的事情并不完全清楚。我认为这只是在需要的地方添加一个换行符的问题。将输出语句更改为fileout.writelnval1I我收到此错误回溯最近一次调用:fileout.writelnval1 AttributeError中的File 8filecomp.py,第25行:“File”对象没有属性“writeln”Ah。。。请尝试fileout.writeval1+'\n'。我的道歉-错误的包裹。罗希特,你让我成为一个好男人。非常感谢。正如我所预料的那样。真棒的男人干杯!为什么每次比赛都要写标题?为什么使用0/1值而不是自然布尔值?按照编辑的方式,即使没有匹配项,也会打印两个列表中的标题匹配项。这就是为什么我添加了一个if条件,这样只有在第一次找到匹配项时才会打印标题。
test = 0
fileout = open('9output.txt', 'w')
for val1 in lines1:
    for val2 in lines2:
        if val1 == val2:
            if test == 0:
                fileout.write("Match in both the lists")
                fileout.write(val1+"\n")
                test = 1
            else:
                fileout.write(val1+"\n")
fileout.close()
if test == 0:
    print("No matches found!")