如何使用Python仅打印csv文件中的前10行?

Ado*_*ble 7 python csv python-3.x

我是Python的新手,我只想打印一个巨大的csv文件的前10行.

到目前为止,这是我的代码,它打印csv文件中的所有行

import csv
with open('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 13

用途itertools.islice:

import csv
from itertools import islice

with open('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in islice(reader, 10): # first 10 only
        print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
Run Code Online (Sandbox Code Playgroud)

在您使用它的同时,您还可以使用operator.itemgetter以使列变得更容易:

import csv
from itertools import islice
from operator import itemgetter

get_columns = itemgetter('survived', 'pclass', 'name', 'sex', 'age')

with open('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in islice(reader, 10): # first 10 only
        print(*get_columns(row))
Run Code Online (Sandbox Code Playgroud)


小智 11

你可以break在10行之后.

import csv
with open('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for i,row in enumerate(reader):
        print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
        if(i >= 9):
            break
Run Code Online (Sandbox Code Playgroud)