Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用readlines读取前N行_Python_Python 3.x_Numpy_Readlines - Fatal编程技术网

Python 使用readlines读取前N行

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

我的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(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]