【发布时间】:2016-09-02 21:41:36
【问题描述】:
目标:如果计数大于实际行数,在except 块中:告诉用户并让他们按回车。将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)))
我目前得到:
文件不包含那么多行,按回车继续打印最大行数:
每次我按回车键。是什么导致了这种不良行为?
【问题讨论】:
-
f.close()完全是多余的;您已经将该文件用作上下文管理器 (with ...) -
for i, k in enumerate(f, 1): count = i循环的目标是什么?如果小于 10000,您是否尝试将count设置为文件中的实际行数? -
我不确定我是否理解您使用无限循环的原因。目标是等待文件获得更多行吗?你不能不重新打开。