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, 2019 in Python by ana1504.k
• 7,910 points
6,651 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]

Hope this will help!

To learn more, go for Python Master course today.

Thank!

answered Apr 16, 2019 by SDeb
• 13,300 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, 2019 in Python by Nymeria
• 3,560 points
927 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, 2019 in Python by Nymeria
• 3,560 points
601 views
–1 vote
2 answers
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
• 58,080 points
1,179 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,810 points
278 views
0 votes
1 answer

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

After what I observed, you would have ...READ MORE

answered Feb 11 in Python by Rahul
• 9,240 points
437 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
• 58,080 points
1,098 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
• 58,080 points
352 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, 2019 in Python by SDeb
• 13,300 points
342 views
0 votes
2 answers

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

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 580 points
833 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP