[英]In Python, how can I read just the first x lines from a file using the “strip() for line in file” format?
[英]I try to parse line by line within a text file in Python , but it just can parse first line, it can not read from second line
我的文本文件“test.txt”看起來像;
主機名開關
網絡 192.168.8.0 255.255.255.0
==================================================== =
我的 python 編碼“TextFileParse.py”;
導入操作系統
f = open('test.txt', 'r')
而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(關閉)
結果消息;
主機名開關
回溯(最后一次調用):文件“D:\TextFileParse.py”,第 15 行,在 nw = item[item.index('network')+1] ValueError: 'network' is not in list
如何從第二行讀取索引? 我不是程序專家,只是初學者。
f.readlines()
一次讀取文件的每一行。 您有程序搜索hostname
和network
,但兩者都不在文件的每一行中。 你可以試試:
try:
name = item[item.index('hostname')+1]
print(name, end=" ")
except ValueError:
nw = item[item.index('network')+1]
print(nw)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.