[英]Compare two files and store unique data in a new file in Python
我有两个文件,其中数据以一种模式存储。 以下是详细信息:
文件 1.txt:
1.1.1.1 -> 0.0.0.0
2.2.2.2 -> 0.0.0.0
3.3.3.3 -> 1.1.1.1
4.4.4.4 -> 2.2.2.2
file1.txt 的模式是这样的:
source ip -> destination ip
文件2.txt:
5.5.5.5
6.6.6.6
2.2.2.2
1.1.1.1
file2.txt 的模式是这样的:
source ip
测试.py:
with open("file1.txt") as fp1, open("file2.txt") as fp2, open("newfile.txt", "w") as fp3:
i = 0
k = 0
while True:
try:
if i == 0:
# at first get line from both file
l1 = next(fp1)
l2 = next(fp2)
# if both the line is equal get another line
if l1 == l2:
try:
l1 = next(fp1)
except StopIteration:
break
l2 = next(fp2)
# if line are not equal then put l1 in new file
else:
fp3.write(l1)
try:
l1 = next(fp1)
except StopIteration:
break
i += 1
except StopIteration:
k += 1
if k == 2:
break
except Exception as e:
print(e)
break
我的代码没有比较这两个文件。 他只是将 file1.txt 数据存储在一个新文件 file3.txt 中。 只比较两个文件的源 ip,并将数据存储在一个新文件中。 存储的数据应该是这样的。 File1.txt 始终与 file2.txt 进行比较。 如果 file2.txt 中不存在 file1.txt 数据,则该数据应存储在新文件 file3.txt 中。 我在下面显示了我的 output:
文件 3.txt:
3.3.3.3 -> 1.1.1.1
4.4.4.4 -> 2.2.2.2
公共数据不应存储在新文件中。 比较两个文件,如果它们都是公共数据,则公共数据将被忽略,唯一数据将存储在一个新文件中。
您只需要一些正则表达式知识。
import re
input1 = open("file1.txt","r")
input2 = open("file2.txt","r")
output = open("output.txt","w")
file2_data = input2.read()
for line in input1:
regex_search = re.search(r"\d.\d.\d.\d", line)
source_ip = regex_search[0]
if re.search(source_ip,file2_data)==None:
output.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.