Tristan Sun
Tristan Sun

Reputation: 299

import CSV file to Python

I am trying to import csv file to Python. I have two question here.

Q1. my code is:

import csv
with open('highfrequency2.csv') as csvfile:
  freq=csv.reader(csvfile, delimiter=',')
  for row in freq:
    print(row[1],row[8])

But there is an error message here

IndexError: list index out of range

Q2. my data output looks like

['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', ''] 
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
.....
....

Do I have to use 'r' or 'rb' function in reading the file ?

I want to see the 2nd and the 8th row of the CSV file.

Upvotes: 1

Views: 1092

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

If you just want rows 2-8, use itertools.islice on the reader object:

import csv
from itertools import islice, izip

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    # create islice object
    interest = islice(freq, 1, 8, None))
    # iterate over islice object getting row at a time
    for row in interest:
       print(row)

If you just want those two specific rows use a step of 6:

 import csv
from itertools import islice, izip

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    interest = islice(freq, 1, 8, 6))
    for row in interest:
       print(row)

Or call next on the reader object after skipping the first line:

import csv

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    next(freq)
    # create generator expression
    interest = (next(freq) for _ in range(7))
    for row in interest:
       print(row)

Or using enumerate:

 import csv

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    interest = (row for ind, row in enumerate(freq) if ind in {1,7})
    for row in interest:
       print(row)

Upvotes: 1

Marek
Marek

Reputation: 1727

your row has 6 elements and you're trying to print the 2nd and the 9th. well, the latter does not exist, hence list index out of range (indexing starts with 0).

Upvotes: 2

Related Questions