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

0 votes

Hey all, pretty straightforward question. I basically want to read a certain set of numbers from a file into an array. In my case, a 2-dimensional array to be precise.

The following are the contents of the file:

A line containing height and weight attributes.

Height attributes containing width attributes which are just integers separated by white space.

Check out the following example:

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

How do I go about doing this? All help appreciated!

Feb 6, 2019 in Python by Anirudh
• 2,080 points

1 answer to this question.

0 votes

Hi, good question.

Let us first assume that you do not have any extra whitespaces present. If this is the case then check out the following piece of code:

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()])

However, this can be further simplified and compressed. That last for loop can be put into a nested list, right?

Check it out here:

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]

This should solve your problem, let me know if you need anything else!

answered Feb 6, 2019 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
0 answers

how can i read a text file in python?

can you specify the syntax and prequisites ...READ MORE

Apr 4, 2019 in Python by Waseem
• 4,540 points
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

how can i extact all the links from a website using python and save it in a csv file ?

Hi, @Shubham, Web scraping is the technique to ...READ MORE

answered Jun 16 in Python by Gitika
• 51,280 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,570 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
0 votes
1 answer

How can I parse a YAML file in Python?

Read & Write YAML files with Python ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,520 points
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,520 points