Skip to content Skip to sidebar Skip to footer

Only Reading First N Rows Of Csv File With Csv Reader In Python

I'm adding the text contained in the second column of a number of csv files into one list to later perform sentiment analysis on each item in the list. My code is fully working for

Solution 1:

The shortest and most idiomatic way is probably to use itertools.islice:

import itertools
...
        for row in itertools.islice(reader1, 200):
            ...

Solution 2:

Pandas is a popular module for manipulating data, like CSVs. Using pandas this is how you could limit the number of rows.

import pandas as pd
# If you only want to read the first 200 (non-header) rows:
pd.read_csv(..., nrows=200)

Solution 3:

You can just add a count, and break when in reaches 200, or add a loop with a range of 200.

Define a variable right before your for loop for rows starts:

count = 0

Then inside your loop:

count = count + 1ifcount== 200: 
    break

Post a Comment for "Only Reading First N Rows Of Csv File With Csv Reader In Python"