How to read numbers from file in Python?

0 votes
I want to read numbers from a file into a two-dimensional array.

The file contents are as follows:

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
Apr 16 in Python by ana1504.k
• 7,890 points
108 views

1 answer to this question.

0 votes
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]
answered Apr 16 by SDeb
• 13,230 points

Related Questions In Python

0 votes
1 answer

How to create and read from a temporary file in Python?

Hi, there is a very simple solution ...READ MORE

answered Jan 29 in Python by Nymeria
• 3,520 points
103 views
0 votes
1 answer

How can I read numbers in Python from a custom file?

Hi, good question. Let us first assume that ...READ MORE

answered Feb 6 in Python by Nymeria
• 3,520 points
87 views
0 votes
1 answer
0 votes
1 answer

How to read Excel File in Python

With pandas it is possible to get ...READ MORE

answered Oct 22, 2018 in Python by Priyaj
• 57,300 points
227 views
0 votes
1 answer

Open file in Python

There is this code I used for ...READ MORE

answered Nov 16, 2018 in Python by Jino
• 5,590 points
40 views
0 votes
1 answer

Crawling after login in Python

You missed a few login data forms, ...READ MORE

answered Sep 7, 2018 in Python by Priyaj
• 57,300 points
454 views
0 votes
1 answer

Crawling after login in Python

You missed a few login data forms, ...READ MORE

answered Sep 14, 2018 in Python by Priyaj
• 57,300 points
47 views
0 votes
1 answer

“stub” __objclass__ in a Python class how to implement it?

You want to avoid interfering with this ...READ MORE

answered Sep 27, 2018 in Python by Priyaj
• 57,300 points
78 views
0 votes
1 answer

How to read a large file, line by line, in Python?

The correct, fully Pythonic way to read ...READ MORE

answered Jul 1 in Python by SDeb
• 13,230 points
43 views
0 votes
1 answer

In Python, how do I read a file line-by-line into a list?

with open(fname) as f:     content = f.readlines() # you ...READ MORE

answered Oct 9, 2018 in Python by SDeb
• 13,230 points
143 views