Isura Nirmal
Isura Nirmal

Reputation: 787

Python csv seek() not working

Hi I am trying to read a csv file using the following code. I want to read from n th line to m th line of the csv file provided. As a example I want to start reading from 10th line to 100 line and after that start from 500th line to 1000th line. I give those parameters using start and end variables.

The problem that it always start from the beginning regardless the start and end variables. i tried and tried for a solution but failed.Can anyone help me to figure out the issue here.? Thanks a lot! (there are some duplicate questions but no one seems to have given a solution)


    import csv
    import os

    with open('file.csv','r') as csvfile:
        start=10
        end=100
        csvfile.seek(start)
        r= csv.reader(csvfile)
        r.next()
        for i in range(start,end):
            try:
                url=r.next()[2]
                print url
            except IndexError,e:
                print str(e),
            except ValueError,b:
                print b
        csvfile.close()

Upvotes: 0

Views: 2462

Answers (2)

ThePavolC
ThePavolC

Reputation: 1738

You can iterate through csv file lines and get lines you want like this:

import csv

def read_lines(file_name, start, end):
    with open(file_name, 'rb') as csvfile:
        csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
        for row in csvreader:
            if csvreader.line_num >= start and csvreader.line_num <= end:
                print ', '.join(row)
            else:
                continue

read_lines('test.csv', 10,12)

Update:

From documentation: csvreader.line_num: The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.

Upvotes: 0

user1907906
user1907906

Reputation:

Use the csv module.

import csv

n = 3
m = 5

read = 0
with open("so.csv") as csvfile:
    reader = csv.reader(csvfile)
    for record in reader:
        read += 1
        if read >= n and read <= m:
            print(record)

Upvotes: 1

Related Questions