gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:30 25 4
gpt4 key购买 nike

目标:如果计数大于实际行数,则在 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:")

关于python - 处理异常时奇怪的嵌套循环行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39301069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com