pythonfilepython-3.x

How to read numbers from file in Python?


I'd like to read numbers from a file into a two-dimensional array.

File contents:

For example:

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

Solution

  • 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]