我对一些在 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 循环中读取我的字符串,或者至少我是这么认为的。有没有快速的方法来解决这个问题?任何帮助表示赞赏。谢谢!
最佳答案
问题是您在同一个文件上使用了 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
。
关于Python 2.7 混合迭代和读取方法会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891143/