【问题标题】:Read first N lines using readlines [duplicate]使用readlines读取前N行[重复]
【发布时间】:2017-03-31 14:36:07
【问题描述】:

我的python代码是这样的

with open('file.txt') as w:
    k = np.asarray(w.readlines(),np.float)

但是当我这样做时,k 是一个数组,所有行都从 file.txt 读取

我试图仅读取第一行 n 并使用 np.asarray 存储 k 如何使用 n 编辑此代码

感谢您的帮助!

【问题讨论】:

  • 你试过readlines()[:n]吗?
  • 是的,谢谢,伙计!傻我
  • 警告[:n] 不适用于大文件(文件必须复制到内存中)。首选第二种方法
  • 新版本的np.genfromtxt 采用max_rows 参数。

标签: python python-3.x numpy readlines


【解决方案1】:
from itertools import islice
with open("file.txt") as myfile:
    k = list(islice(myfile, n))
print k

with open('file.txt') as w:
    k = np.asarray(w.readlines(),np.float)
    k = k[:,n]

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多