这个函数是一个更大的类的一部分,这个函数的目的是使用第一行最后一个元素作为键并使用s_d
作为值来制作一个字典。 c
应该用于其他事情。当我打印new_dict
时,我得到了所需的结果,但循环一直在运行
def extract(filename):
f = open(filename)
new_dict={}
c = ''
l = f.readline().strip()
while l :
first = f.readline().strip()[-1]
s_d = f.readline().strip()
l = f.readline().strip()
new_line= f.readline().strip()
while new_line != 'FIN' :
c = c + new_line
new_line = f.readline().strip()
new_dict[first]= s_d
print(new_dict)
这个函数必须以这种方式完成,有两个while循环。如何在函数用完后停止运行
顺便说一句 文本文件如下:
IDS
ID 0
text(small description of item)
text(long description)
text(long desc second line)
FIN
ID 1
same as before
答案 0 :(得分:0)
检查readline()函数返回的值是否为空字符串。如果是,你已到达最后一行,你可以休息。 https://docs.python.org/2/tutorial/inputoutput.html
答案 1 :(得分:0)
将s_d
添加到点击更新l
为l = new_line
后。这将确保while l:
始终检查从文件中读取的最后一行。