-1
  • I have a CSV file.

  • How do I read specific rows?

  • I want to read the rows in the even positions?

import csv
with open('source.csv','rt')as f:
  data = csv.reader(f)
  for row in data:
        print(row)
  • 4
    Stack Overflow is not a free programming service. Show us the code you already have! – Klaus D. Mar 01 '21 at 11:12
  • Does this answer your question? [How can I skip even/odd rows while reading a csv file?](https://stackoverflow.com/q/61087934/2745495) – Gino Mempin Mar 01 '21 at 11:54

3 Answers3

1
import pandas as pd

dataframe = pd.read_csv('your_file')
dataframe_even_rows = dataframe.iloc[::2]
Adrien
  • 433
  • 1
  • 3
  • 13
0

here you go:

import csv

even_rows = []
# reading the csv
with open("file.csv", "r+") as csv_file:
    # reading all lines
    lines = csv.reader(csv_file, delimiter=",")
    
    # extracting only even lines
    for i, line in zip(range(lines.line_num), lines):
        if i % 2 == 0:
            even_rows.append(line)

# printing output
for row in even_rows:
    print(row)
alexzander
  • 1,586
  • 1
  • 9
  • 21
0

Extending the solution provided by Adrien.

import pandas as pd
n = 1   #Number of rows you want to skip
dataframe = pd.read_csv('your_file')
dataframe_even_rows = dataframe.iloc[::(n+1)]
dataframe_specific_row = dataframe.iloc[2] #Specific lines: read third line(index start at 0)