我有一些问题可以在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
Run Code Online (Sandbox Code Playgroud)
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])
Run Code Online (Sandbox Code Playgroud)
这会返回一个错误:
ValueError: Mixing iteration and read methods would lose data.
Run Code Online (Sandbox Code Playgroud)
我知道问题是我如何在while循环中读取我的字符串,或者至少这是我所相信的.有没有快速解决方法?任何帮助表示赞赏.谢谢!
问题是您正在使用next和使用readline相同的文件.正如文档所说:
.由于使用预读缓冲区,将next()与其他文件方法(如readline())结合使用是行不通的.
修复是微不足道的:替换next为readline.