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 in Python by Anirudh
• 2,070 points
87 views

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 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 in Python by Waseem
• 4,480 points
32 views
0 votes
1 answer
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,810 points
243 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,420 points
136 views
+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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 405 views
+4 votes
6 answers
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
3,112 views
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
100 views