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

时间:2015-11-24 10:26:48

标签: 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循环中读取字符串的方式,或者至少我认为是这样。有没有快速解决方法?任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:5)

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

  

。使用预读缓冲区的结果是,将next()与其他文件方法(如readline())相结合是行不通的。

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

答案 1 :(得分:0)

如果您想要一个简短的代码,请尝试:

lines = []
with open(filename) as f:
    lines = [line for line in f if line.strip()]

然后你可以对线进行测试。