【问题标题】:How to print only first few lines of output through python code?如何通过python代码只打印前几行输出?
【发布时间】:2023-03-23 16:54:01
【问题描述】:

在 python 2.7 中是否有一种特殊的方法/函数可以只打印前几行输出。我们知道在终端中我们可以通过“$head -3”来查看前 3 行。我是不是只需要写一个 python for 循环。

【问题讨论】:

  • 如果我没记错的话,那个循环应该是 2 行,正好比 head -3 多 1 行。
  • 是的...for i in xrange(3): print next(...)
  • 如果你想用几个字符,你可以用 text[:30] 作为前 30 个字符

标签: python python-2.7 output large-data


【解决方案1】:

我正在使用大型 xml,它产生的输出比控制台显示的要多。 我正在使用:

import lxml.etree as etree

print etree.tostring(large_xml_root)[0:300]

仅查看此 xml 的开头。

这不正是您所要求的,但我在这篇文章中寻找类似上述解决方案的东西。

【讨论】:

    【解决方案2】:
    import sys 
    
    class Logger(object):
        def __init__(self, n):
            self.n = n 
            self.count = 0 
            self.terminal = sys.stdout
    
    
        def write(self, message):
            self.count+=1
            if self.count<self.n:
                self.terminal.write(message)
    
    
    sys.stdout = Logger(10)
    

    现在当你使用 print 时,只会打印前 10 行,其他行将被忽略

    【讨论】:

      【解决方案3】:
      with open('file1.txt') as f:
          for i in xrange(3):
              print f.readline()
      

      【讨论】:

        猜你喜欢
        • 2012-11-27
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 1970-01-01
        • 2015-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多