处理异常时出现奇怪的嵌套循环行为

时间:2016-09-02 21:41:36

标签: python file

目标:如果count大于实际行数,则在except块中:告诉用户并让他们按Enter键。将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)))

我目前正在:

  

文件不包含那么多行,按回车键继续打印最大行:

每次按下回车键。造成这种不良行为的原因是什么?

1 个答案:

答案 0 :(得分:2)

您已经耗尽了该文件,您无法再次从文件中读取,而不会回到0.因此,您的for i, k in enumerate(f, 1):循环会立即退出。这同样适用于while 1:循环的每个未来迭代;该文件仍在最后,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行,则每次都必须重新打开该文件并寻找最后记录的位置:< / p>

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:")