【问题标题】:Loadtext for specific number of lines特定行数的加载文本
【发布时间】:2015-09-14 07:28:29
【问题描述】:

我有一个巨大的文件要加载,所以我无法直接打开它。我想我必须分多个部分阅读它。

例如,为了使用第 1 到 50 行,我尝试了类似的方法,但它不起作用:

import numpy as np

with open('test.txt') as f:
    lines = (line for line in f if line < 50.)
    FH = np.loadtxt(lines, delimiter=',', skiprows=1)

【问题讨论】:

  • lines = [f.readline() for _ in range(50)]

标签: python numpy text


【解决方案1】:

当您使用numpy 时,您可以使用内置itertools 库中的islice() 函数仅加载前50 行,如下所示:

import numpy as np
import itertools

with open('test.txt') as f_input:
    FH = np.loadtxt(itertools.islice(f_input, 0, 50), delimiter=',', skiprows=1)

【讨论】:

    【解决方案2】:

    Numpy 1.16 开始,np.loadtxt 带有一个可选参数max_rows,它限制了要读取的行数:

    import numpy as np
    
    np.loadtxt('file.txt', max_rows=50, delimiter=',', skiprows=1)
    

    【讨论】:

      【解决方案3】:

      在 Python 3 中,请尝试以下操作:

      a = 0
      f = open('test.txt')
      while a < 50:
          a = a + 1
          print(f.readline(), end='')
      else:
          f.close()
      

      在 Python 2 中,使用这个:

      a = 0
      f = open('test.txt')
      while a < 50:
          a = a + 1
          print f.readline(),
      else:
          f.close()
      


      或者选择这种方式,使用readlines():

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

      readlines() 会创建一个列表,一行是一个对象。所以如果你想要 20 - 50 行,你可以这样做:

      for i in text[20:50]:
          print(i)
      

      【讨论】:

      • 当我从 0 开始时效果很好,但如果我想考虑从 10 开始,我该怎么做?感谢您的帮助
      • 我尝试使用 print f.readline()[10:] 但它在“水平数据”上播放
      • 最简单的方法:使用readline()阅读前10行使用此解决方案,不要打印它们。然后你可以阅读文件考虑从 10 开始。
      • 对不起,我看到了一些困难:/你能修改代码部分吗?
      • 完成了,我认为readlines()是最好的方法:)
      【解决方案4】:

      我使用函数从文件中读取任意第一行、最后 N 行:

      def read_first_last_N_lines_from_file(in_file,N,last=False):
          with open(in_file) as myfile:
              if last:
                  return [x.strip() for x in list(myfile)][-N:]
              return [next(myfile).strip() for x in range(N)]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-25
        • 1970-01-01
        • 2014-09-28
        • 2015-05-13
        相关资源
        最近更新 更多