How to read numbers from file in Python?

I’d like to read numbers from file into two dimensional array.

File contents:

  • line containing w, h
  • h lines containing w integers separated with space

For example:

4 3
1 2 3 4
2 3 4 5
6 7 8 9

Answer

Assuming you don’t have extraneous whitespace:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

You could condense the last for loop into a nested list comprehension:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]