繁体   English   中英

如何在python中获得以下输出

[英]How to get the following ouput in python

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

目前我得到的输出为:

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!")

检查这是否有效。 要在单独的行中书写,您可以使用"\\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!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM