faqts : Computers : Programming : Languages : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 5 of 5 people (100%) answered Yes

Entry

How do I read a text file containing lines of 5 integers into a list of lists but not as strings?

Jan 10th, 2007 16:56
Reed O'Brien, Paul Benson,


given a file with the following lines:
1 2 3 4 5
5 4 3 2 1
11 22 33 44 55
12 34 56 78 90
1 2 1 2 1
THe following:
#!/usr/bin/env python
fh = open('/tmp/tmp.txt')
L = []
for line in fh:
    line = line.strip()
    L1 = [int(x) for x in line.split()]
    L.append(L1)
print L
produces:
[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [11, 22, 33, 44, 55], [12, 34, 56,
78, 90], [1, 2, 1, 2, 1]]
is that what you are looking for?