How to read numbers from file in Python? How to read numbers from file in Python? python-3.x python-3.x

How to read numbers from file in Python?


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]


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

You'll need open(name, mode), myfile.readlines(), mystring.split(), int(myval), and then you'll 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 modefile_handle = open('mynumbers.txt', 'r')# Read in all the lines of your file into a list of lineslines_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 matrixmy_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 I'd often end up building custom functions to construct each kind of array I wanted.


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(r'c:\file.txt', 'r') as f:    w, h  = map(int, f.readline().split())    tmp = []    for i, line in enumerate(f):        if i == h:            break        tmp.append(map(int, line.split()[:w]))    output.append(tmp)