【问题标题】:Python - How to get the number of lines in a text file [duplicate]Python - 如何获取文本文件中的行数[重复]
【发布时间】:2015-12-12 23:13:15
【问题描述】:

我想知道是否可以在不使用以下命令的情况下知道有多少行包含我的文件文本:

with open('test.txt') as f:
    text = f.readlines()
    size = len(text)

我的文件很大,所以很难用这种方法...

【问题讨论】:

    标签: python python-3.x file text count


    【解决方案1】:

    作为 Pythonic 方法,您可以使用 sum 函数中的生成器表达式计算行数,如下所示:

    with open('test.txt') as f:
       count = sum(1 for _ in f)
    

    注意这里的文件对象f 是一个迭代器对象,它表示文件行的迭代器。

    【讨论】:

      【解决方案2】:

      对您的方法稍作修改

      with open('test.txt') as f:
          line_count = 0
          for line in f:
              line_count += 1
      
      print line_count
      

      注意事项:

      在这里你将逐行浏览,不会将完整的文件加载到内存中

      【讨论】:

        【解决方案3】:
        with open('test.txt') as f:
            size=len([0 for _ in f])
        

        【讨论】:

          【解决方案4】:

          文件的行数不存储在元数据中。所以你实际上必须运行整个文件才能弄清楚。不过,您可以提高内存效率:

          lines = 0
          with open('test.txt') as f:
              for line in f:
                  lines = lines + 1
          

          【讨论】:

            猜你喜欢
            • 2021-02-28
            • 2013-05-13
            • 2015-03-23
            • 2015-09-09
            • 2018-05-14
            • 1970-01-01
            • 2021-06-22
            • 2017-10-17
            • 2019-03-08
            相关资源
            最近更新 更多