我有2个文本文件,我想比较一个与另一个的内容。 需要检查Unique.txt中的ip是否存在于CheckIp.txt中。 我的代码如下:
with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
for line in fp:
print(line)
with open("/root/nix_bsd_mac_inventory-master/CheckIp.txt") as fp1:
for line1 in fp1:
line1 = line1.rstrip()
if line == line1:
print (line1 + "Ip is Already Present")
else:
print ("Processing Ip:"+ line)
看来我做错了。有人可以帮助我吗?
答案 0 :(得分:0)
也许您还应rstrip()
Unique.txt
中CheckIp.txt
的行,与Unique.txt
一样,删除新行和其他杂散尾随空格。这可能会解决它。
不是为Unique.txt
中的每一行打开第二个文件,而是将第二个文件读入一个集合,然后将with open('/root/nix_bsd_mac_inventory-master/CheckIp.txt') as f:
ips = set(line.rstrip() for line in f)
with open('/root/nix_bsd_mac_inventory-master/Unique.txt') as f:
for line in f:
line = line.rstrip()
if line in ips:
print('{}: Ip is Already Present'.format(line))
else:
print('Processing Ip: {}'.format(line))
中的行与集合中的行进行比较:
REGEXP
答案 1 :(得分:0)
此代码应该适合您:正在检查Unique.txt
中是否找到了CheckIp
的内容。
with open("Unique.txt") as firstFile:
checkIP = firstFile.read().strip()
with open("CheckIp.txt") as secondFile:
contents = secondFile.read().strip()
if checkIP in contents:
print ("{} IP is Already Present".format(checkIP))
else:
print ("Processing Ip: {}".format(checkIP))
但是,如果两个文件只包含您要比较的IP,那么您可以进行更具体的检查:
if checkIP == contents:
print ("{} IP is Already Present".format(checkIP))
else:
print ("Processing Ip: {}".format(checkIP))
答案 2 :(得分:-1)
考虑您的文件" Unique.txt" 只是会包含您正在寻找的IP:
f1 = open('CheckIp.txt', 'r')
data= ''.join(f1.readlines())
f2 = open('Unique.txt','r')
toFind = f2.readline()
if data.find(toFind) != -1:
print("ip "+toFind+" found!")
else:
print("ip "+toFind+" not found!")