【发布时间】:2021-12-19 03:25:58
【问题描述】:
我想知道如何从文本文件中打印出每个接口及其各自的 IP 地址。 这是下面的文本文件:
eth0 Link encap:Ethernet HWaddr b8:ac:6f:65:31:e5 inet addr:192.168.2.100
Bcast:192.168.2.255 Mask:255.255.255.0 inet6 addr: fe80::baac:6fff:fe65:31e5/64
Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2697529
errors:0 dropped:0 overruns:0 frame:0 TX packets:2630541 errors:0 dropped:0
overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:2159382827 (2.0 GiB) TX
bytes:1389552776 (1.2 GiB)
eth1 Link encap:Ethernet HWaddr b8:ac:6f:65:53:e5 inet addr:10.10.2.100 Bcast:10.10.2.255
Mask:255.255.255.0 inet6 addr: fe80::baac:6fff:ff65:31e5/64 Scope:Link UP BROADCAST RUNNING
MULTICAST MTU:1500 Metric:1 RX packets:2697529 errors:0 dropped:0 overruns:0 frame:0 TX
packets:2630541 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX
bytes:2159382827 (2.0 GiB) TX bytes:1389552776 (1.2 GiB)
我已经对此进行了几次尝试。呈现给我的方式是把它变成一个列表并从那里解析它。
这是我尝试过的:
#Initializing a list
txt_lst = []
txt_file = open('ipaddress.txt', 'r', encoding = "utf8")
txt_lines = txt_file.readlines()
#Checks the length of the txtfile and list
sz = len(txt_lines)
#Adds each line to a list, essentially converting the textfile to a list
for line in txt_lines:
txt_lst.append(line)
#Splitting each line by comma to create sentences for this textfile
new_txt_lst = [line.split(",") for line in txt_lst]
这就是我想要格式化输出的方式:
interface name | ip address
eth0 |192.168.2.100
eth1 |10.10.2.100
任何帮助将不胜感激。谢谢!!
【问题讨论】:
-
你能告诉我在哪里可以得到这些信息吗?我一直在努力,但是使用这个文本文件很复杂。
-
在空行上拆分文本 -
\n\n(双新行) - 然后第一个单词将是interface name。如果您在inet addr:上拆分,那么第一个“单词”将是IP address -
for line in txt_lines: txt_lst.append(line)给出与txt_lst = txt_line.copy()相同的结果-但似乎浪费时间-您应该直接使用txt_line而不是txt_lst
标签: python string parsing extract