python - while 循环如果到达文件末尾则终止

标签 python file while-loop increment termination

如果到达文件末尾,则 while 循环终止

最佳答案

在Python中,文件对象实现了__iter__接口(interface),这样你就可以:

for line in file:
   # processing on line

我的建议是以这种方式重组代码,如有必要,请尽早中断。例如:

for line in file:
  if processed_count >= max_lines_to_process:
     break
  # ....
  processed_count += 1

关于python - while 循环如果到达文件末尾则终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23534689/

相关文章:

python - 我无法理解 python3 中的导入

php - 使用 HTML5 和 PHP 加载多个文件

r - 如何将 2 个单独的分类变量编码为 R 中的一个?

c++ - 如何阻止它无限重复,但仍保持循环?

python - 我们可以在 pytest 中有多个 addfinalizer

Python将xml转换为列表

python - 在Python中,使find_monthly_ savings函数返回金额除以一年中的月份(十二个月)的正确方法是什么

java - 使用文件集合,获取与特定文件夹相关的 getPath()

c - 当用户输入 "quit"时使 while 循环不打印(在用户说退出但程序结束后仍打印 STR)

python - 将英寸转换为米、磅转换为千克时获取小数值