以下是一个示例代码,用于比较两个包含IP地址的文件并返回不共同的IP地址:
def compare_ip_addresses(file1, file2):
# 读取文件1中的IP地址并存储到一个集合中
with open(file1, 'r') as f1:
ips1 = set(f1.read().splitlines())
# 读取文件2中的IP地址并存储到一个集合中
with open(file2, 'r') as f2:
ips2 = set(f2.read().splitlines())
# 找到不共同的IP地址
different_ips = ips1.symmetric_difference(ips2)
return different_ips
# 使用示例
file1 = 'file1.txt'
file2 = 'file2.txt'
result = compare_ip_addresses(file1, file2)
print(result)
请确保将file1.txt
和file2.txt
替换为实际包含IP地址的文件的路径。这个示例代码假设每个文件中每行只包含一个IP地址。compare_ip_addresses
函数使用了Python的集合(set)数据结构来存储IP地址,然后使用symmetric_difference
方法找到不共同的IP地址。最后,将结果打印出来。