使用python2.x在windows中选择两行之间的所有行

2024-05-20 19:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我试图操纵的数据。你知道吗

开始放映功能

功能名称实例状态


bash shell 1已禁用

bfd 1禁用

bgp 1已禁用

节目结束功能

我正在尝试获取两行之间的数据。你知道吗

下面是一个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}

到目前为止,我已经为python2.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(这可能会有帮助,但是) 但是不行。你知道吗

如果将提取的数据/行存储到变量中,也会有很大帮助。你知道吗


Tags: of数据infrom功能showlinemyfile
2条回答
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,我才找到了这个解决方案。你知道吗

print lines[fromline..toline]

怎么样:

print lines[fromline:toline] 

It would also greatly help if the extracted data/lines are stored into a variable. doesnt work, it errors out.

你是怎么做到的?你犯了什么错误?你知道吗

相关问题 更多 >