Easy question

Jose' Sebrosa sebrosa at artenumerica.com
Wed Apr 11 19:32:52 EDT 2001


Duncan Smith wrote:
> 
> I need to read some data from a file.  Each (tab delimited) row corresponds
> to an array index eg.
> 
> 0    0    0    0    0    0
> 0    1    0    0    0    0
> 0    0    1    0    0    0
> ...
> 
> And I need something like,
> 
> [[0,0,0,0,0,0], [0,1,0,0,0,0], [0,0,1,0,0,0], ...]
> 
> What's the best way of doing this?  Cheers in advance.

To read the file line by line into a list:

list_of_lines = open('your_file').readlines()

[Check the description of the readlines() method of file objects]

To make a list of columns out of each (string) line:

import string
list_of_columns_str = string.split(line)

[Note: This way the line is split by groups of blanks, either tabs, spaces or
other blanks -- check the description of the function split() of the module
string.  If you really need to split by tabs, you can use 
string.split(line, '\t') -- but then you need to discard the last '\n'
character of each line...]

Doing the same with conversion of the columns (strings) in the list to
integers:

import string
list_of_columns_int = map(int, string.split(line))

Put it together:

import string
the_list_you_want = map(lambda line: map(int, string.split(line)),
                        open('your_file').readlines())

This is cute but not robust against small syntax deviations.  For example, if
your file has blank lines, you will get empty lists in the_list_you_want, which
may or may not be what you want!

You feel more confortable with "unrolled" code. If so, you may write it like
this:

import string
the_list_you_want = []
for line in open('filename').readlines():
    the_list_you_want.append(map(int, string.split(line)))

Sebrosa

--
http://artenumerica.com/



More information about the Python-list mailing list