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
7,495 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
2,048 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
1,129 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,020 points
1,738 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,820 points
783 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, 2022 in Python by Rahul
• 9,680 points
1,944 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,020 points
1,675 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,020 points
853 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
868 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,300 points
1,791 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP