我希望获得python文件中的前n行数据。为了得到一行,我会做next(file)
;为了得到多行,我会做file.read(1024)
或''.join(file.readlines()[:1000]
。你知道吗
在函数中实现这一点的最佳方法是什么?这是一个开始:
def get_first_n_rows(self, file, n=1):
"""
Will return a string of the first N lines of data from the file.
"""
s = ''
with open(file, 'r') as f:
for line in f:
s += line
if line == n: break
return s
有没有更好的方法可以让我使用一个interator,比如next
?你知道吗
使用islice:
从链接的文档中:
或者,如果您想要一个行列表:
相关问题 更多 >
编程相关推荐