擅长:python、mysql、java
<p>使用<a href="https://docs.python.org/3.7/library/itertools.html#itertools.islice" rel="nofollow noreferrer">islice</a>:</p>
<pre><code>from itertools import islice
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 islice(f, n):
s += line
return s
</code></pre>
<p>从链接的文档中:</p>
<blockquote>
<p>Make an iterator that returns selected elements from the iterable. If
start is non-zero, then elements from the iterable are skipped until
start is reached. Afterward, elements are returned consecutively
unless step is set higher than one which results in items being
skipped.</p>
</blockquote>