我正在尝试仅在python中打印文件的前5行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我正在尝试仅在python中打印文件的前5行相关的知识,希望对你有一定的参考价值。

我只想打印文件的前5行,但是当行数大于5时,它会打印多次。这是我的代码:

numLines = 0
with open("points_sorted", "r") as f:
  for line in f:
    pointsList = line.split()
    numLines += 1
    if numLines >= 5:
      from itertools import islice
      with open("points_sorted") as myfile:
        head = list(islice(myfile, 5))
        print(head)

这是我的文件:

101 
87 M
71 Ko
55 Ko
15 Ko
15 M
0 M Ko

有人可以帮助我完成我的程序吗?

答案

您可以在满足条件后使用break语句退出循环:

numLines = 0
with open("points_sorted", "r") as f:
  for line in f:
    pointsList = line.split()
    numLines += 1
    if numLines >= 5:
      break

您也可以使用enumerate(),因此您不必手动计算行数:

with open("points_sorted", "r") as f:
  for numLines, line in enumerate(f):
    pointsList = line.split()
    if numLines >= 4: # counting now starts at 0 instead of 1
      break
另一答案

您可以通过这种方式尝试

with open("points_sorted", "r") as f:
 cnt = 5
 while(cnt > 0):
   pointsList = f.readline().split()
   cnt = cnt -1

以上是关于我正在尝试仅在python中打印文件的前5行的主要内容,如果未能解决你的问题,请参考以下文章