Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why csv.reader is not pythonic?

Tags:

python

csv

I started to use the csv.reader in Python 2.6 but you can't use len on it, or slice it, etc. What's the reason behind this? It certainly feels very limiting.

Or is this just an abandoned module in later versions?

like image 974
Joan Venge Avatar asked Apr 17 '09 17:04

Joan Venge


People also ask

What is the difference between CSV reader and CSV DictReader?

csv. Reader() allows you to access CSV data using indexes and is ideal for simple CSV files. csv. DictReader() on the other hand is friendlier and easy to use, especially when working with large CSV files.

How do I open a CSV file in Python read mode?

At first, the CSV file is opened using the open() method in 'r' mode(specifies read mode while opening a file) which returns the file object then it is read by using the reader() method of CSV module that returns the reader object that iterates throughout the lines in the specified CSV document.


1 Answers

I'm pretty sure you can't use len or slice because it is an iterator. Try this instead.

import csv
r = csv.reader(...)
lines = [line for line in r]
print len(lines) #number of lines
for odd in lines[1::2]: print odd # print odd lines
like image 190
job Avatar answered Sep 27 '22 18:09

job