Python 2.7 混合迭代和读取方法会丢失数据

标签 python python-2.7

我对一些在 Python 3 中有效但在 2.7 中失败的代码有疑问。我有以下部分代码:


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])

这会返回一个错误:

    ValueError: Mixing iteration and read methods would lose data. 

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

最佳答案

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

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

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

关于Python 2.7 混合迭代和读取方法会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891143/

相关文章:

python - asyncio 是否允许多个实现共存?

javascript - JavaScript 是否将哈希表用于 Map 和 Set?

python - 使用python登录站点并在浏览器中打开登录站点

python - 引用数组

python - 在同一更新中更新文档和嵌套文档

python - 有没有办法将我从 .txt 文件中检索到的整数相加

python - golang 像 python 一样定义 dict,并将值附加到 dict 中的列表

python - Numpy savez 异常

python - 对象模型来实现tranches,如何实现?

python pdfkit : increase font size