python-3.x - python3映射两个文件之间的唯一值并合并两个文件中的唯一行
问题描述
我正在弄清楚两个文件之间的唯一值,如果两个文件中都存在唯一值,我想将两个文件中的行合并为一行。
更明确地说,我正在寻找MAC ADDRESS
第三列,以file1
使该键成为一个键并希望对其进行匹配file2
,如果匹配,则将文件的两个匹配项合并到一行中。
文件 1
192.168.100.1 0 001c.0718.1ed6 Vlan100, Port-Channel230
192.168.100.2 0 fa16.3e88.245d Vlan100, Port-Channel230
192.168.100.3 0 001c.0718.1f52 Vlan100, Port-Channel230
192.168.100.4 0 001c.0724.tb6a Vlan100, Port-Channel51
192.168.100.5 0 01c.0718.1t9c Vlan100, Port-Channel230
192.168.100.6 0 fa16.3ed8.dd6c Vlan100, Port-Channel27
192.168.100.7 0 fa16.3e22.20c3 Vlan100, Port-Channel230
192.168.100.8 0 fa16.3ecd.e1db Vlan100, Port-Channel27
192.168.100.9 0 001c.0718.9c8f Vlan100, Port-Channel230
文件2
4 001c.0724.tb6a DYNAMIC Po17 1 13 days, 22:08:51 ago
4 001c.0718.1f52 DYNAMIC Po15 1 12 days, 5:07:20 ago
4 001c.0718.1ed6 DYNAMIC Po11 1 12 days, 5:05:44 ago
4 001c.0718.1t9c DYNAMIC Po9 1 12 days, 5:07:16 ago
4 001c.0718.9c8f STATIC Po9 1 12 days, 5:07:16 ago
代码:下面是我根据模式尝试的代码,并适合我从谷歌找到的示例,但它在执行时抛出错误。
!#/usr/bin/python3
# port_details.py
mapping_dict = {}
INPUT_FILE_1 = 'file1'
INPUT_FILE_2 = 'file2'
with open(INPUT_FILE_1) as file1:
while True:
line = file1.readline()
print(line)
if not line:
break
#_, mac, _, port = line.strip()
ip_addr, _, mac, _, status = line.split()
mapping_dict[mac.lower()] = status
with open(INPUT_FILE_2) as file2:
while True:
line = file2.readline()
if not line:
break
#ip_addr, _, mac, _ = line.strip()
_, value_id, _, port = line.split()
status = mapping_dict.get(mac, '')
print(ip_addr, mac, port, status)
错误在运行时,我尝试了不同的错误值,但没有让它运行仍然四处张望,任何提示或建议将不胜感激。
Traceback (most recent call last):
File "./srdjan1.py", line 13, in <module>
ip_addr, _, mac, _, status = line.split()
ValueError: not enough values to unpack (expected 5, got 4)
期望值是:
192.168.100.1 001c.0718.1ed6 Po11 Vlan100 Port-Channel230
解决方案
我得到了解决方案,使用字典来保存值以及re
空格。
import re
INPUT_FILE_1 = 'file1.txt'
INPUT_FILE_2 = 'file2.txt'
dict1 = {}
dict2 = {}
def fl2():
with open(INPUT_FILE_2) as file2:
while True:
line = file2.readline()
if not line:
break
data1 = re.split("\s+",line)
dict1[data1[2]] = data1[4]
file2.close()
return dict1
with open(INPUT_FILE_1) as file1:
dict2 = fl2()
while True:
line = file1.readline()
if not line:
break
data = re.split("\s+",line)
if data[2] in dict2:
print(data[0],data[2],dict2[data[2]])
结果符合预期:
./port_details.py
192.168.1.1 001001c Good
推荐阅读
- html - 将设计转录为 HTML 和 CSS
- python - Django:Formset 不保存为条目已存在
- c - 在C中连接十六进制字节
- html - 在这个超级简单的示例中,如何模糊黑框/边框?
- angular - 初始FormGroup失败后Angular 7反应形式patchValue为null
- java - 有没有办法更新JVM堆中每个对象的引用?
- sockets - 仅在调试模式下工作的套接字反应本机
- c++ - 如何实现链表类的单项?
- google-chrome-extension - 如何使用 chrome 插件打开 chrome 应用程序?
- php - 替换 .xml 文件中的无效 URI