需要在Python中阅读特定范围的文本文件

时间:2014-01-18 17:07:54

标签: python file python-2.7

我需要在特定行之后读取文本文件,然后说#100行。此行具有特定数字,例如“255”。然后我想用for循环阅读接下来的500行。在那500行我有一些数字要提取。如在P [3]位置。然后我需要将这些值传递给数组。最后我应该有几套如下。我使用以下代码来做到这一点。但我失败了。任何人都可以帮助我。

文件如下所示

Generated by trjconv : a bunch of waters t=   0.00000
 500
    1SOL     OW    1   1.5040   2.7580   0.6820
    2SOL     OW    4   1.5210   0.9510   2.2050

  500SOL     OW 2998   1.5310   1.7952   2.1981
   3.12736   3.12736   3.12736
Generated by trjconv : a bunch of waters t= 9000.00000
 500
    1SOL     OW    1   1.5040   2.7580   0.6820
    2SOL     OW    4   1.5210   0.9510   2.2050

  500SOL     OW 2998   1.5310   1.7952   2.1981
   3.10941   3.10941   3.10941
Generated by trjconv : a bunch of waters t=   0.00000
 500
    1SOL     OW    1   1.5040   2.7580   0.6820
    2SOL     OW    4   1.5210   0.9510   2.2050

  500SOL     OW 2998   1.5310   1.7952   2.1981
   3.12736   3.12736   3.12736
Generated by trjconv : a bunch of waters t= 9000.00000
 500
    1SOL     OW    1   1.5040   2.7580   0.6820
    2SOL     OW    4   1.5210   0.9510   2.2050

  500SOL     OW 2998   1.5310   1.7952   2.1981
   3.10941   3.10941   3.10941

编码我写过

F = open('Data.gro', 'r')
A = open('XYZ.txt', 'w')
XO = []
I = range(1,500)
for line in F:
    P = line.split()
    if P[0] == '256': # after i found this I want to read next five hundred lines.
        for R in I:
            P = line.split()
                        XO.append(P[3])
                        R +=1

    # after the for loop I want write 'XO' in to file as set 01 then should go to next P[0] == '256'

结果应如下文件名'XYZ.txt'

Set 01
X = [1.32, 4.132, 2.23, .... upto 500]
Set 02
X = [4.232, 1.162, 3.73, .... upto 500]

1 个答案:

答案 0 :(得分:4)

你只需要获取内部循环中的行,你可以使用next()

with open('filename') as f:
    for line in f:
       if line.split()[0] == '256':
          for _ in xrange(500):
              line = next(f)
              #do something with line

在上面的代码中,如果文件在条件为True后没有500行,则会出现StopIteration错误,您可以使用try-except或者使用itertools.islice

的文件对象
from itertools import islice
with open('filename') as f:
    for line in f:
       if line.split()[0] == '256':
          XO =[line.split(None, 4)[3] for line in islice(f, 500)]
          #Write XO to a file

如果这些行不以前导空格开头,那么您可以使用@ zhangxaochen建议将line.split()[0] == '256'部分替换为line.startswith('256 ')。另一个选择是使用line.split(None, 1)[0] == '256',它只会将该行拆分一次。