Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read ahead in a file when looping through it with Python?

Tags:

python

file

I am looping through a file and if I find something, would like to read ahead several lines looking for something before returning control to the main loop. However, I want to return control at the point that I stopped looking ahead.

Sample code:

for line in file:
    line = line.strip()
    llist = line.split()

    if llist[0] == 'NUMS':
        # some loop to read ahead and print nums on their own line
        #   until it finds END, then return control to the main for
        #   loop at the point where it stopped looking ahead.

Sample input:

NUMS
1
2
3
4
5
END
SOME
MORE
STUFF
NUMS
6
7
8
9
0
END

Desired output:

1 2 3 4 5
6 7 8 9 0

I am fairly new at Python, so if there is a better way to do it besides using a loop for look ahead, I'm happy to see it.

like image 307
astay13 Avatar asked Nov 18 '11 22:11

astay13


People also ask

How do you go to the next line while reading a file in Python?

Python File next() Method Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.

How do you read a loop file in Python?

To do that, first, open the file using Python open() function in read mode. The open() function will return a file handler. Use the file handler inside your for-loop and read all the lines from the given file line by line. Once done,close the file handler using close() function.

How do you read until the end of a file in Python?

The readlines () method is the most popular method for reading all the lines of the file at once. This method reads the file until EOF (End of file), which means it reads from the first line until the last line. When you apply this method on a file to read its lines, it returns a list.

Can you read a file multiple times in python?

Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.


1 Answers

It's not a good idea to read ahead if you don't need to, which is the case here. What you need to do can be accomplished in a single for loop, by maintaining one bit of state. This allows for error checking, and scales up to much more complicated requirements than can be handled by nested loops over the same iterator.

guff = """NUMS
1
2
etc etc
9
0
END"""

state = ""
for item in guff.split():
    if item == "NUMS":
        if state == "NUMS": print "missing END"
        state = "NUMS"
    elif item == "END":
        if state == "": print "missing NUMS"
        state = ""
        print
    elif state == "NUMS":
        print item,

if state == "NUMS": print # missing END
like image 148
John Machin Avatar answered Sep 30 '22 18:09

John Machin