我正在尝试使用“from itertools import islice”,以便使用 liblas 模块一次从 *.las 文件中读取多行。 (我的目标是逐块阅读)
按照问题:Python如何一次读取N行 https://stackoverflow.com/questions/6335839/python-how-to-read-n-number-of-lines-at-a-time
islice() 可用于获取迭代器的下 n 个项目。因此,
list(islice(f, n)) 将返回文件接下来 n 行的列表
F。在循环中使用它将为您提供 n 个块的文件
线。在文件末尾,列表可能会更短,最后
该调用将返回一个空列表。
我使用了以下代码:
from numpy import nonzero
from liblas import file as lasfile
from itertools import islice
chunkSize = 1000000
f = lasfile.File(inFile,None,'r') # open LAS
while True:
chunk = list(islice(f,chunkSize))
if not chunk:
break
# do other stuff
但我有这个问题:
len(f)
2866390
chunk = list(islice(f, 1000000))
len(chunk)
**1000000**
chunk = list(islice(f, 1000000))
len(chunk)
**1000000**
chunk = list(islice(f, 1000000))
len(chunk)
**866390**
chunk = list(islice(f, 1000000))
len(chunk)
**1000000**
当文件 f 最后到达时,islice 重新开始读取文件。
感谢您的任何建议和帮助。非常感谢
编写一个生成器一次生成 n 行似乎很容易:
def n_line_iterator(fobj,n):
if n < 1:
raise ValueError("Must supply a positive number of lines to read")
out = []
num = 0
for line in fobj:
if num == n:
yield out #yield 1 chunk
num = 0
out = []
out.append(line)
num += 1
yield out #need to yield the rest of the lines
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)