Re: Reading a two-column file into an array?



Marc 'BlackJack' Rintsch <bj_666@xxxxxxx> 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
.



Relevant Pages

  • Re: [NEWB] Dictionary instantiation?
    ... I'm working with csv module as an exercise to parse out a spreadsheet ... def author_to_dict: #Function to add each author to the dictionary ... Please take a little time to read more material about functions and scoping rules. ... read more material, experiment (Python is great for this - read about the '-i' option of the python interpreter), and post here when you run into trouble. ...
    (comp.lang.python)
  • Re: parsing csv files class
    ... I just want to make it more pythonic I also want to add capability for makeing csv file if I give it input like: ... On Sat, Dec 27, 2008 at 4:54 AM, alex goretoy ... #!/usr/bin/env python ... def index: ...
    (comp.lang.python)
  • Re: csv nil check and update
    ... newFile << ... Do you need to preserve the redundant quotes in the output? ... require 'CSV' ... def fill ...
    (comp.lang.ruby)
  • csv and mixed lists of unicode and numbers
    ... I want to put data from a database into a tab separated text file. ... import csv, codecs, cStringIO ... class UnicodeWriter: ... def writerows: ...
    (comp.lang.python)
  • [NEWB] Dictionary instantiation?
    ... I'm working with csv module as an exercise to parse out a spreadsheet ... def author_to_dict: #Function to add each author to the dictionary ... #Function to remove entries with '' in the ... csv_list = list#Convert the open file to list format ...
    (comp.lang.python)