Python 2.7 混合迭代和读取方法会丢失数据 [英] Python 2.7 mixing iteration and read methods would lose data

查看:44
本文介绍了Python 2.7 混合迭代和读取方法会丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些代码在 Python 3 中有效,但在 2.7 中失败了.我有以下部分代码:

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

车站

    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. 

我知道问题在于我如何在 while 循环中读取字符串,或者至少我是这么认为的.有没有快速解决这个问题的方法?任何帮助表示赞赏.谢谢!

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!

推荐答案

问题是您在同一个文件上使用 nextreadline.正如文档所说:

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

.由于使用了预读缓冲区,因此将 next() 与其他文件方法(如 readline())结合使用时无法正常工作.

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

修复很简单:将 next 替换为 readline.

The fix is trivial: replace next with readline.

这篇关于Python 2.7 混合迭代和读取方法会丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆