python从指定行开始读取,python - 从文本的特定行读取文件

I'm not talking about specific line numbers because i'm reading multiple files with the same format but vary in length.

Say i have this text file:

Something here...

... ... ...

Start #I want this block of text

a b c d e f g

h i j k l m n

End #until this line of the file

something here...

... ... ...

I hope you know what i mean. i was thinking of iterating through the file then search using regular expression to find the line number of "Start" and "End" then use linecache to read from Start line to End line.

But how to get the line number? what function can i use?

解决方案

If you simply want the block of text between Start and End, you can do something simple like:

with open('test.txt') as input_data:

# Skips text before the beginning of the interesting block:

for line in input_data:

if line.strip() == 'Start': # Or whatever test is needed

break

# Reads text until the end of the block:

for line in input_data: # This keeps reading the file

if line.strip() == 'End':

break

print line # Line is extracted (or block_of_lines.append(line), etc.)

In fact, you do not need to manipulate line numbers in order to read the data between the Start and End markers.

The logic ("read until…") is repeated in both blocks, but it is quite clear and efficient (other methods typically involve checking some state [before block/within block/end of block reached], which incurs a time penalty).

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值