【python】有规律的文本中读取指定的行

最近在学习python,正好工作中遇到一个问题,正好拿来练练手。

User 3%, System 16%, IOW 0%, IRQ 0%
User 11 + Nice 0 + Sys 51 + Idle 246 + IOW 0 + IRQ 0 + SIRQ 0 = 308

  PID CPU% S  #THR     VSS     RSS UID      Name
22843   5% R     1    940K    380K root     top
 1638   1% S     9 121264K  15544K app_17   com.SecureUpgrade
 1261   0% S    14 109184K  17032K app_16   com.db4o.servo.search
  821   0% S     1   1204K    540K root     /opl/third_party/mesh/mesh
  830   0% S     1    720K    360K root     /system/bin/logcat



User 3%, System 14%, IOW 0%, IRQ 0%
User 12 + Nice 0 + Sys 47 + Idle 255 + IOW 0 + IRQ 0 + SIRQ 1 = 315

  PID CPU% S  #THR     VSS     RSS UID      Name
22843   3% R     1    948K    396K root     top
 1261   1% S    14 109184K  17032K app_16   com.db4o.servo.search
 1638   0% S     9 121264K  15564K app_17   com.SecureUpgrade
  821   0% S     1   1204K    540K root     /opl/third_party/mesh/mesh
  834   0% S     1    720K    364K root     /system/bin/logcat

 我要处理的正如你看到的上面的文本,事实上我想要的只是第8行(实际的文本开头还有3行空行)开始往下的5行内容。它的规律就是每隔7行后面5行才是我需要的。

于是就用python写了一个小程序,代码如下:

 1 def ReadFile(fp, start_line, read_scope):
2 lines = fp.readlines()
3 cursor = 0
4 for line in lines:
5 line = line.rstrip()
6 cursor += 1
7 while (cursor > start_line):
8 return line
9 if (cursor == (start_line+read_scope)):
10 cursor = 0
11 break
12 fp.close()

说明:

fp:是要读写的文件,你可以用下面的代码定义:

1 fp = open('file')

start_line:可以理解为你要跳过的行数

read_scope:是你要读取的行数

例如,ReadFile(fp, 7, 5)就是从第8行开始读取5行内容

posted @ 2012-02-28 21:52  whuiscool  阅读(2139)  评论(0编辑  收藏  举报