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:
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
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)
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.