Skip to main content
 首页 » 编程设计

python之处理异常时奇怪的嵌套循环行为

2024年10月17日9wuhuacong

目标:如果计数大于实际行数,则在 except block 中:告诉用户并让他们按回车键。设置 count 等于文件中的总行数并重试循环。

count = 10000 
with open('mobydick_ch1.txt') as f: 
 
        while 1: 
            lines = [] 
            try: 
                for i in range(count): 
                    lines.append(next(f))  # iterate through file and append each line in range 
                    break 
            except StopIteration: 
                if not input("File does not contain that many lines, press enter to continue printing maximum lines:"): 
                    for i, k in enumerate(f, 1): 
                        count = i 
 
        f.close()  # close file 
 
        # format output. enumerate lines, start at 1 
        # http://stackoverflow.com/questions/4440516/in-python-is-there-an-elegant- 
        # way-to-print-a-list-in-a-custom-format-without-ex 
    print(''.join('Line {0}: {1}'.format(*k) for k in enumerate(lines, 1))) 

我目前得到:

File does not contain that many lines, press enter to continue printing maximum lines:

每次我按回车键。是什么导致了这种不良行为?

请您参考如下方法:

你已经耗尽了文件,你不能再次读取文件而不返回0。结果你的for i, k in enumerate(f, 1) : 循环立即退出。这同样适用于 while 1: 循环的每个 future 迭代;文件仍在末尾,所有使用 next() 的访问都会立即引发 StopIteration。

你已经知道你读了多少行,只需设置count = len(lines)。无需为了设置 count 而再次读取整个文件。

如果用itertools.islice()就更好了得到你的 1000 行:

from itertools import islice 
 
count = 10000 
with open('mobydick_ch1.txt') as f: 
    lines = list(islice(f, count))  # list of up to count lines 
if len(lines) < count: 
    input("File does not contain that many lines, press enter to continue printing maximum lines:") 
    count = len(lines)  # set count to actual number of lines 

如果您试图等待直到文件包含至少 count 行,您将不得不每次重新打开文件并寻找最后记录的地点:

lines = [] 
pos = 0 
while len(lines) < count: 
    with open('mobydick_ch1.txt') as f: 
        f.seek(pos) 
        lines.extend(islice(f, count - len(lines))) 
        pos = f.tell() 
    if len(lines) < count: 
        input("File does not contain that many lines, press enter to continue printing maximum lines:")