Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to read specific range of text file in Python

I need to read a text file after specific line let say line # 100. This line has specific number such as '255'. Then i want to read next 500 lines using for loop. in those 500 line i have some numbers to extract. Such as in P[3] position. Then I need to pass those value into an array. At the end I should have few sets like below. I used following code to do that. But i failed. Can any one help me.

File looks like below

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

Coding I have written

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'

Results should be like below in file name 'XYZ.txt'

Set 01
X = [1.32, 4.132, 2.23, .... upto 500]
Set 02
X = [4.232, 1.162, 3.73, .... upto 500]
like image 950
Shanaka Avatar asked Jan 18 '14 17:01

Shanaka


People also ask

How do you read multiple lines in a text file in Python?

To read multiple lines, call readline() multiple times. The built-in readline() method return one line at a time. To read multiple lines, call readline() multiple times.

How do you go to a specific line of code in Python?

getline("Quotes. txt", number) #Create a new variable in order to grab the specific line, the variable #integer can be replaced by any integer of your choosing. print(lines) #This will print the line of your choosing. If you are completing this in python make sure you have both files (.


1 Answers

You just need to fetch the lines inside the inner loop as well, you can use next() for that:

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

In the above code you'll get a StopIteration error if the file doesn't have 500 lines after the condition is True, you can handle that either using a try-except or take a slice of the file object using 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

If the lines don't start with leading spaces then you can use @zhangxaochen suggestion to replace the line.split()[0] == '256' part with line.startswith('256 '). Another option is to use line.split(None, 1)[0] == '256', which is going to split the line only once.

like image 135
Ashwini Chaudhary Avatar answered Sep 30 '22 09:09

Ashwini Chaudhary