Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print only the first 10 lines from a csv file using Python?

I'm new to Python and I'm wanting to print only the first 10 lines of a huge csv file.

Here's my code so far that prints all of the lines in the csv file

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'])
like image 456
Adorabubble Avatar asked May 07 '16 12:05

Adorabubble


1 Answers

Use 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'])

While you're at it, you can also make use of operator.itemgetter to make the column getting a bit easier:

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))
like image 132
Jon Clements Avatar answered Oct 20 '22 00:10

Jon Clements