如何在python中获取以下输出

时间:2018-08-15 20:17:03

标签: python python-3.x python-2.7 scripting devops

我正在尝试比较两个具有子网并能够获得输出结果的文本文件。 但是我需要以正确的格式输出(逐行) 我还想添加一条打印语句,作为“在两个列表中都匹配”

当前我得到的输出为:

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

代码

#Open the first file and read in each line as
#a value in a list called lines1. After reading
#each line, then strip off any extra whitespace
#or typeset characters.
with open('6output.txt') as f1:
    lines1 = f1.readlines()
    lines1 = [x.strip() for x in lines1]
f1.close()
#Open the second file and read in each line as
#a value in a list called lines2. After reading
#each line, then strip off any extra whitespace
#or typeset characters.
with open('7subnet.txt') as f2:
    lines2 = f2.readlines()
    lines2 = [x.strip() for x in lines2]
f2.close()
#Loop over each element in the two lists. If a
#match is found, then we write the value to the
#output file. If there is no match, output info.
test = 0
fileout = open('9output.txt', 'w')
for val1 in lines1:
    for val2 in lines2:
        if val1 == val2:
            fileout.write(val1)
test = 1
fileout.close()
if test == 0:
    print("No matches found!")

1 个答案:

答案 0 :(得分:1)

检查是否可行。要用单独的行书写,可以使用"\n"。 id是,您只想将短语“在两个列表中都匹配”放置一次,则需要添加一个附加的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!")