Reading a two-column file into an array?

Alex Martelli aleax at mac.com
Tue Jul 31 17:41:45 CEST 2007


Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:

> On Mon, 30 Jul 2007 21:57:17 -0700, Nagarajan wrote:
> 
> > a = []
> > import csv
> > reader = csv.reader(open("filename", "r"), delimiter='\t' )
> > for row in reader:
> >     a.append( row )
> 
> I would keep a reference to the file to close it properly and the loop can
> be replaced by a call to `list()`:
> 
> import csv
> 
> def main():
>     data_file = open('filename', 'rb')
>     a = list(csv.reader(data_file, delimiter='\t'))
>     data_file.close()

That's what 2.5's with statement is all about...:

from __future__ import with_statement

def main():
    with open('filename', 'rb') as f:
        return list(csv.reader(f, delimiter='\t'))


Alex



More information about the Python-list mailing list