这是我试图操纵的数据。
功能名称实例状态
禁用bash-shell 1
bfd 1已停用
bgp 1禁用
我想在2行之间获取数据。
这是一个powershell示例
$from = ($switchinfo | Select-String -pattern "start of show feature" | Select-Object LineNumber).LineNumber
$to = ($switchinfo | Select-String -pattern "end of show feature" | Select-Object LineNumber).LineNumber -gt $from
$a = $switchinfo | where {$_.readcount -gt $from -and $_.readcount -lt $to}
到目前为止,我已经为python 2.7.12
了fromStr = 'start of show feature'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if fromStr in line:
fromline = num
toString = 'end of show feature'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if toString in line:
toline = num
f=open(filepath)
lines=f.readlines()
print lines[toline]
注意:filepath是一个变量,它是文件&的完整路径。文件名本身。
print lines[toline]
作品
print lines[fromline]
作品
print lines[fromline..toline]
不起作用,它出错了。我想知道我是否能在这方面得到一些帮助。 我已经提到了Reading specific lines only (Python) 和 Python read specific lines of text between two strings(这可能有帮助但是) 但是没有去。
如果将提取的数据/行存储到变量中,也会有很大帮助。
答案 0 :(得分:1)
print lines[fromline..toline]
怎么样:
print lines[fromline:toline]
如果将提取的数据/行存储到变量中,这也会有很大帮助。不起作用,它出错了。
你是怎么做到的?你得到了哪个错误?
答案 1 :(得分:1)
filename = "somepath/somefilename.txt"
f=open(filename )
lines=f.readlines()
fromStr = 'start of show feature'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if fromStr in line:
fromline = num
toString = 'end of show feature'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if toString in line:
toline = num
store = lines[fromline:toline+1]
cutstore = '\n'.join(store)
print cutstore
感谢skycc& drjohn,我能够达到这个解决方案。