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?
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With