Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert txt file to int array

I have a text file which looks something like:

-45 64 -41 -51
  95 96 -74     -74 56 41
41 64    -62 75

and I'm trying to convert it into an int array.

So far I tried making it one big String then convert it like that, but when I tried getting rid of the white spaces, the output still looks exactly like the txt file.

file = open("dir", "r")
line = file.read()
line.strip()
line.replace(" ","")
print line
line.close()

What am I doing wrong? Can I just read it from the file straight into an int array?

like image 310
Rasheed Billy Avatar asked Feb 06 '23 14:02

Rasheed Billy


2 Answers

You're almost there - you need to use str.split instead of str.strip and str.replace. Then map the result to integers. You can also use a context manager that will close the file (not a line, by the way) automatically.

with open('dir') as f:
    content = file.read()
array = content.split()
numbers = map(int, array)
print array
like image 93
TigerhawkT3 Avatar answered Feb 08 '23 04:02

TigerhawkT3


Using list comprehension, an answer would be:

with open('dir', 'r') as f:
    data = f.read()

res = [int(i) for i in data.split()]

Output:

>>> res
[-45, 64, -41, -51, 95, 96, -74, -74, 56, 41, 41, 64, -62, 75]
like image 28
ettanany Avatar answered Feb 08 '23 03:02

ettanany