Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are several methods to read a specific number of rows from a CSV file, but here are three common ways to do so:

  1. Using a loop to read a certain number of rows:
import csv

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    row_count = 0
    num_rows = 10 # Set the number of rows to read
    for row in reader:
        if row_count < num_rows:
            print(row)
            row_count += 1
        else:
            break
  1. Using the islice function from the itertools module:
import csv
from itertools import islice

with open('file.csv', 'r') as file:
    reader = csv.reader(file)
    num_rows = 10 # Set the number of rows to read
    for row in islice(reader, num_rows):
        print(row)
  1. Using Pandas library:
import pandas as pd

df = pd.read_csv('file.csv', nrows=10)
print(df)

Each method has its advantages and disadvantages depending on your use case, so choose the one that suits your needs the best.