我想从一个文件中读取4行,并将每行放入一个单独的变量中。据我所知,我不能使用:
for file in f
因为它一次只需要一行,并且我需要将4行放入4个独立的变量中
我目前的“解决方案”是这样的:
while f.readline != None:
tempName = f.readline()
print(tempName)
tempColour = f.readline()
tempAge = f.readline()
tempWeight = f.readline()
# this try is taking the varables and making an object
try:
tempSheep = Sheep(tempName, tempColour, int(tempAge), int(tempWeight))
except:
print("your file is in an improper format")
break
else:
sheepList.append(tempSheep)
据我所知,问题在于将变量放入对象中。程序运行正常,然后由于某些原因运行了额外的时间,在这种情况下,变量没有正确填充兼容的数据类型,并且类抛出错误。
最后,我想我的问题是:如何让循环正确退出?
它超出了文件的末尾,将变量设置为none,然后在创建对象时抛出错误。
如果这篇文章很乱,我很抱歉,这是我第一篇关于堆栈溢出的文章。
转载请注明出处:http://www.beijingklxcmc.com/article/20230526/2261202.html