Skip to content Skip to sidebar Skip to footer

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('tit

Solution 1:

Use itertools.islice:

import csv
from itertools import islice

withopen('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    forrowin islice(reader, 10): # first10only
        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')

withopen('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in islice(reader, 10): # first 10 onlyprint(*get_columns(row))

Solution 2:

You could just break after 10 lines.

import csv
withopen('titanic.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for i,rowin enumerate(reader):
        print(row['survived'], row['pclass'], row['name'], row['sex'], row['age'])
        if(i >=9):
            break

Solution 3:

To get top N lines from a csv file, with select fields

#for python 3import csv
from operator import itemgetter
N=11# to get 10 rows need use 10+1=11
fname='titanic.csv'
get_columns=itemgetter('survived', 'pclass', 'name', 'sex', 'age')

withopen(fname,'r') as csvfile:
    reader = csv.DictReader(csvfile.readlines()[0:N])
    [print(*get_columns(row)) for row in reader]

     # or for all fields : use [print(row)) for row in reader]

Post a Comment for "How Do I Print Only The First 10 Lines From A Csv File Using Python?"