user12589
user12589

Reputation: 27

How to read integers in a file in Python?

I want to read integers in a file using Python. There are some solutions but it does not work in my case. My file looks like this

50:32 9 5 436 475 3453
40:53 63 634 26 62
44:545 63 6246 6344 6346 44
90:52 6346 65 634 63

I tried this code

for line in fr.readlines():
  Semi = line.split(':')
  Targets.append(int(Semi[0]))
  Space = line.split(' ')
  cubes.append(int(Space[1]))

But it does not work the output

[50, 40, 44, 90]

I need to read integers before (:) and store them in an array (Actually I did it successfully). But I need to store every line in an array for example the first line

[32, 9, 5, 436, 475, 3453]

Upvotes: 0

Views: 2460

Answers (2)

Chris Charley
Chris Charley

Reputation: 6573

Here is a possible way which uses re.split(... to get the ints into a variable and the rest into a list.

k, *rest = map(... assigns the int before the colon to k and the ints after the colon to rest.

re.split(r'\D+' It splits on nondigits, (colon, space).

import re

data = """\
50:32 9 5 436 475 3453
40:53 63 634 26 62
44:545 63 6246 6344 6346 44
90:52 6346 65 634 63""".splitlines()

targets = []
cubes = []

for line in data:
    line = line.rstrip()
    k, *rest = map(int, re.split(r'\D+', line))
    targets.append(k)
    cubes.append(rest)

print(targets)
print(cubes)

Prints:

[50, 40, 44, 90]

[[32, 9, 5, 436, 475, 3453], [53, 63, 634, 26, 62], [545, 63, 6246, 6344, 6346, 44], [52, 6346, 65, 634, 63]]

Upvotes: 2

Goldwave
Goldwave

Reputation: 599

This splits by : removes the newline at the end. Then it iterates over the string of numbers, returning an array of the numbers. Then we append that to our numberArrays variable.

File = open('file').readlines()
numberArrays = []
for line in File:
    numbers = line.split(':')[1][:-1]
    numberArray = [ int(number) for number in numbers.split(' ')]
    numberArrays.append(numberArray)
print(numberArrays)

output

[[32, 9, 5, 436, 475, 3453], [53, 63, 634, 26, 62], [545, 63, 6246, 6344, 6346, 44], [52, 6346, 65, 634, 6]]

Alternatively you can just work with the number array in the loop like this

File = open('file').readlines()
for line in File:
    numbers = line.split(':')[1][:-1]
    numberArray = [ int(number) for number in numbers.split(' ')]
    print(numberArray)

Which outputs

[32, 9, 5, 436, 475, 3453]
[53, 63, 634, 26, 62]
[545, 63, 6246, 6344, 6346, 44]
[52, 6346, 65, 634, 6]

Upvotes: 4

Related Questions