擅长:python、mysql、java
<p>使用<code>csv</code>模块,然后计算行数(使用<a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow noreferrer">^{<cd2>} function</a>或使用<a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow noreferrer">^{<cd3>}</a>来限制读取量:</p>
<pre><code>import csv
output = []
with open( 'test.csv', 'r', newline='') as f:
reader = csv.reader(f)
for counter, row in enumerate(reader):
if counter > 2:
# read only the header and first two rows
break
output.append(row[:2])
</code></pre>
<p>或者使用<code>islice()</code>:</p>
<pre><code>import csv
from itertools import islice
with open( 'test.csv', 'r', newline='') as f:
reader = csv.reader(f)
output = list(islice((row[:2] for row in reader), 3))
</code></pre>