How to read numbers from file in Python?

How to read numbers from file in Python?

Assuming you dont 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]

To me this kind of seemingly simple problem is what Python is all about. Especially if youre coming from a language like C++, where simple text parsing can be a pain in the butt, youll really appreciate the functionally unit-wise solution that python can give you. Id keep it really simple with a couple of built-in functions and some generator expressions.

Youll need open(name, mode), myfile.readlines(), mystring.split(), int(myval), and then youll probably want to use a couple of generators to put them all together in a pythonic way.

# This opens a handle to your file, in r read mode
file_handle = open(mynumbers.txt, r)
# Read in all the lines of your file into a list of lines
lines_list = file_handle.readlines()
# Extract dimensions from first line. Cast values to integers from strings.
cols, rows = (int(val) for val in lines_list[0].split())
# Do a double-nested list comprehension to get the rest of the data into your matrix
my_data = [[int(val) for val in line.split()] for line in lines_list[1:]]

Look up generator expressions here. They can really simplify your code into discrete functional units! Imagine doing the same thing in 4 lines in C++… It would be a monster. Especially the list generators, when I was I C++ guy I always wished I had something like that, and Id often end up building custom functions to construct each kind of array I wanted.

How to read numbers from file in Python?

Not sure why do you need w,h. If these values are actually required and mean that only specified number of rows and cols should be read than you can try the following:

output = []
with open(rc:file.txt, r) as f:
    w, h  = map(int, f.readline().split())
    tmp = []
    for i, line in enumerate(f):
        if i == h:
        tmp.append(map(int, line.split()[:w]))

Leave a Reply

Your email address will not be published.