Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 mixing iteration and read methods would lose data

I have an issue with a bit of code that works in Python 3, but fail in 2.7. I have the following part of code:


def getDimensions(file,log):
noStations = 0 
noSpanPts = 0 
dataSet = False

if log:
    print("attempting to retrieve dimensions. Opening file",file)

while not dataSet:      
    try: # read until error occurs
        string = file.readline().rstrip() # to avoid breaking on an empty line
    except IOError:
        break

stations

    if "Ax dist hub" in string: # parse out number of stations
        if log:
            print("found ax dist hub location") 
        next(file) # skip empty line
        eos = False # end of stations
        while not eos:
            string = file.readline().rstrip()
            if string =="":
                eos = True
            else:
                noStations = int(string.split()[0])

This returns an error:

    ValueError: Mixing iteration and read methods would lose data. 

I understand that the issue is how I read my string in the while loop, or at least that is what I believe. Is there a quick way to fix this? Any help is appreciated. Thank you!

like image 572
olivier petit Avatar asked Feb 09 '23 11:02

olivier petit


1 Answers

The problem is that you are using next and readline on the same file. As the docs say:

. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

The fix is trivial: replace next with readline.

like image 81
strubbly Avatar answered Feb 12 '23 10:02

strubbly