我正在尝试比较两个有子网的文本文件,并能够得到输出。但我需要正确格式的输出(逐行)。我还想添加一条print语句作为"Match in the both lists“。
目前,我得到的输出如下:
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!")
发布于 2018-08-16 04:34:26
检查这是否起作用。要在不同的行中编写代码,可以使用"\n"
。和id如果你只想在两个列表中放一次"Match in the lists“,你就需要另外放一条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!")
https://stackoverflow.com/questions/51865819
复制相似问题