Ask Your Question
0

What is the method to read a specific number of rows from a CSV file?

asked 2023-06-09 20:25:37 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-09 20:29:02 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-09 20:25:37 +0000

Seen: 16 times

Last updated: Jun 09 '23