csv iterator question

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Fri May 23 17:58:56 EDT 2008


On Fri, 23 May 2008 13:36:55 -0700, davidj411 wrote:

> example of open method on file object:
> fhandle=open(filename).readelines()

Here the name `fhandle` is somewhat misleading.  You don't bind the file
object to that name, but the result of the call of the `readlines()`
method.  Which is a list of lines.  If you would have bound the file
object, you'd observe similar behavior to your CSV reader example.

> example of csv.reader method:
> reader = csv.reader(open(csvfilename))

Because here you are binding the reader object.  Throw in a `list()` to
read all CSV records into a list:

records = list(csv.reader(open(csv_filename)))

In both cases you don't close the file explicitly which might cause
problems.  That CPython closes it for you almost immediately is an
implementation detail.  Other implementations might let those open files
stay open for much longer.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list