2014-01-18 117 views
7

我需要在特定行之後讀取文本文件,假定行號爲100.此行具有特定的編號,例如'255'。然後我想讀取下500行使用for循環。在這500行中,我有一些數字要提取。如在P [3]的位置。然後我需要將這些值傳遞給一個數組。最後,我應該有如下幾組。我用下面的代碼來做到這一點。但我失敗了。誰能幫我。需要閱讀Python中特定範圍的文本文件

文件看起來像下面

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] 
+0

難道你不想在每個500循環之後將'XO'重置爲'[]'嗎? –

回答

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 

在上面的代碼,如果文件不具有500線後的條件爲True,你會得到一個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.startswith('256 ')更換line.split()[0] == '256'部分。另一種選擇是使用line.split(None, 1)[0] == '256',它將僅分割一行。

+0

也許'line.startswith('256')'如果文件太大會快一點嗎? – zhangxaochen

+0

@zhangxaochen如果每一行包含大量的列和行不包含領先的空格,那麼這肯定會有所幫助,否則'line.split(None,1)[0] =='256''也似乎很好。 –

+0

遺憾忘記;) – zhangxaochen