python中返回到哪一行_在Python中如何通过字符搜索跳到一行

在不知道垃圾数据的大小或扫描垃圾数据的情况下,您无法直接查找它。但是,将文件包装在^{}中以丢弃行并不难,直到您看到“良好”的数据,之后它将遍历所有剩余的行:import itertools

# Or def a regular function that returns True until you see the line

# delimiting the beginning of the "good" data

not_good = '# The stuff I care about\n'.__ne__

with open(filename) as f:

for line in itertools.dropwhile(not_good, f):

... You'll iterate the lines at and after the good line ...

如果您确实需要适当定位文件描述符,而不仅仅是行,那么这个变量应该可以工作:

^{pr2}$

如果您真的需要(而不是仅仅需要偏移量),您可以调整它以获得实际的行号。但是它的可读性稍差,因此如果需要,通过enumerate显式迭代可能更有意义(留作练习)。让Python为您工作的方法是:from future_builtins import map # Py2 only

from operator import itemgetter

with open(filename) as f:

linectr = itertools.count()

# Get first good line

# Pair each line with a 0-up number to advance the count generator, but

# strip it immediately so not_good only processes lines, not line nums

good_start = next(itertools.dropwhile(not_good, map(itemgetter(0), zip(f, linectr))))

good_lineno = next(linectr) # Keeps the 1-up line number by advancing once

# Seek back to undo the read of the first good line:

f.seek(-len(good_start), io.SEEK_CUR)

# f is now positioned at the beginning of the line that begins the good data

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值