Python 使用readlines读取前N行
我的python代码是这样的Python 使用readlines读取前N行,python,python-3.x,numpy,readlines,Python,Python 3.x,Numpy,Readlines,我的python代码是这样的 with open('file.txt') as w: k = np.asarray(w.readlines(),np.float) 但当我这样做时,k是一个数组,所有行都从file.txt读取 我正在尝试使用np.asarray如何使用n编辑此代码,仅读取前n行并存储k 谢谢你的帮助 from itertools import islice with open("file.txt") as myfile: k = list(islice(myfi
with open('file.txt') as w:
k = np.asarray(w.readlines(),np.float)
但当我这样做时,k是一个数组,所有行都从file.txt读取
我正在尝试使用np.asarray
如何使用n
编辑此代码,仅读取前n
行并存储k
谢谢你的帮助
from itertools import islice
with open("file.txt") as myfile:
k = list(islice(myfile, n))
print k
或
你试过了吗?
readlines()[:n]
?成功了,谢谢!警告[:n]
不适用于大文件(文件必须复制到内存中)。第二种方法是首选的新版本的np.genfromtxt
采用max\u rows
参数。
with open('file.txt') as w:
k = np.asarray(w.readlines(),np.float)
k = k[:,n]