Need Help Parsing From File

Gabriel Genellina gagsl-py at yahoo.com.ar
Wed Dec 6 23:02:08 EST 2006


At Thursday 7/12/2006 00:20, John Frame wrote:

>Like, if in the txt file, I had the following matrix formatted numbers
>with 5 rows and 10 columns, and each number is separated by a single space:
>
>11 12 13 14 15 16 17 18 19 20
>21 22 23 24 25 26 27 28 29 30
>31 32 33 34 35 36 37 38 39 40
>41 42 43 44 45 46 47 48 49 50
>51 52 53 54 55 56 57 58 59 60
>
>How would I read this data from the file into a two dimensional array in
>Python?

If "two dimensional array" means "a list of 5 elements each one being 
a list of 10 integers" you can do this:

ftxt=open(filename,"rt")
arr = []
for line in ftxt:
     arr.append([int(number) for number in line.split()])
ftxt.close()

or, not so legible but more compact:

ftxt=open(filename,"rt")
arr2 = [[int(number) for number in line.split()] for line in ftxt]
ftxt.close()

or using Python 2.5:

with open(filename,"rt") as ftxt:
     arr3 = [[int(number) for number in line.split()] for line in ftxt]


-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list