1

I am trying to extract specific information from a .txt file. I have figured out a way to isolate the lines I need; however, printing them has proven to be problematic.

with open('RCSV.txt','r') as RCSV:
   for line in RCSV.read().splitlines():
      if line.startswith('   THETA'):
           print(line.next())

When I use line.next() it gives me this error:

"AttributeError: 'str' object has no attribute 'next'"

Here is a link to the .txt file
Here is a link to the area of the file in question

What I'm trying to do is extract the line following the line that starts with 'THETA PHI' etc.

Georgy
  • 12,464
  • 7
  • 65
  • 73
Mike
  • 11
  • 4
  • `RCSV.read().splitlines()` returns a list of lines. – Abdul Niyas P M Apr 02 '18 at 07:16
  • You can't call `line.next()`, not just because strings don't have a `next` method, but because strings are just strings; they don't know that they came out of an iterator. The thing you want to call `next` on is the iterator. If you just iterated directly over the file (instead of reading the whole file into memory and then splitting it into lines and storing them all in a list just to get the same lines the file would have already given you), `next(RCSV)` would do that. Although I'm not sure it's actually what you want (it usually isn't). – abarnert Apr 02 '18 at 07:17
  • I answered a very closely related question yesterday. https://stackoverflow.com/questions/49599623/python-search-string-from-output-variable-and-print-next-two-lines/49599785#49599785 – Jean-François Fabre Apr 02 '18 at 07:32

4 Answers4

1

you could use next(input), as:

with open('RCSV.txt', "r") as input:
    for line in input:
        if line.startswith('   THETA'):
           print(next(input), end='')
           break
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

You can use a flag to get all lines after you find the key.

Ex:

with open('RCSV.txt','r') as RCSV:
    content = RCSV.readlines()
    flag = False                         #Check Flag
    for line in content:
        if not flag:
            if line.startswith('   THETA'):
                flag = True
        else:
            print(line)                  #Prints all lines after '   THETA'

Or if you need just the following line.

with open('RCSV.txt','r') as RCSV:
    for line in RCSV:
        if line.startswith('   THETA'):
            print(next(RCSV))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can try this:

with open('RCSV.txt','r') as RCSV:
    for line in RCSV:
        if line.startswith('   THETA'):
            next_line = RCSV.readline() # or RCSV.next()
            print(next_line)

Note that on your next iteration, line will be the line after next_line.

Jonathan Dayton
  • 554
  • 3
  • 13
0

String object has no attribute next, next is an attribute of file object. so fileobject.next() returns the next line i.e. RCSV.next().

Mehul Jain
  • 468
  • 4
  • 12