python中文件读取,如何从Python中的文件读取数字?

I'd like to read numbers from file into two dimensional array.

File contents:

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

解决方案

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]