My Text file 'test.txt' looks like;
hostname Switch
network 192.168.8.0 255.255.255.0
===================================================
My python coding "TextFileParse.py";
import os
f = open('test.txt', 'r')
while 1:
lines = f.readlines()
for line in lines:
item = line.split()
print(line)
name = item[item.index('hostname')+1]
nw = item[item.index('network')+1]
print(name, nw)
f(close)
The result message;
hostname Switch
Traceback (most recent call last): File "D:\TextFileParse.py", line 15, in nw = item[item.index('network')+1] ValueError: 'network' is not in list
How can I read the index from second line? I am not Program expert, just beginner.
f.readlines()
reads every line of the file at a time. You have the program searching for hostname
and network
, but both aren't in each line of the file. You could try:
try:
name = item[item.index('hostname')+1]
print(name, end=" ")
except ValueError:
nw = item[item.index('network')+1]
print(nw)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.