How to read numbers from file in Python?

Viewed 340556

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
6 Answers

To make the answer simple here is a program that reads integers from the file and sorting them

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

After reading each line of the file converting each string to a digit

nums.sort()

Sorting the numbers

f.close()

f = open("input.txt", 'w')
for num in nums:
    f.write("%d\n" %num)

f.close()

Writing them back As easy as that, Hope this helps

The shortest I can think of is:

with open("file") as f:
    (w, h), data = [int(x) for x in f.readline().split()], [int(x) for x in f.read().split()]

You can seperate (w, h) and data if it looks neater.

Related