0

I was wondering as I'm kinda new to python, how may I convert my txt file as :

-20.92060089 -27.72520065 -27.55229950 -20.92469978 -27.69650078 -27.55340004 -20.92469978 -27.69890022 -27.55170059 

To arrays thats kind :

[[-20.92060089, -27.72520065, -27.55229950], [-20.92469978, -27.69650078, -27.55340004], [-20.92469978, -27.69890022, -27.55170059]] 
4
  • Take a look at python's csv module Commented Oct 13, 2020 at 10:51
  • The CSV module doesn't really help here, because it's not comma-separated value input. Commented Oct 13, 2020 at 10:52
  • @JamesMcPherson it's space separated. The delimiter can be configured. Commented Oct 13, 2020 at 10:55
  • @Wups it's still overkill for this minimal use-case though. Commented Oct 13, 2020 at 10:56

1 Answer 1

2

Each of these lines can be split on " ", and you can use a list comprehension to grab this all at once.

I saved your text file as /tmp/tfile.txt, so then I can do this:

>>> array = [ line.split() for line in open("/tmp/tfile.txt").readlines() ] >>> array [['20.92060089', '-27.72520065', '-27.55229950'], ['-20.92469978', '-27.69650078', '-27.55340004'], ['-20.92469978', '-27.69890022', '-27.55170059']] >>> len(array) 3 >>> array[0] ['20.92060089', '-27.72520065', '-27.55229950'] >>> array[1] ['-20.92469978', '-27.69650078', '-27.55340004'] >>> array[2] ['-20.92469978', '-27.69890022', '-27.55170059'] 
Sign up to request clarification or add additional context in comments.

2 Comments

Ok thanks but we agree that I got string with this code ?
Sure - and if you want to make those into floats, do the conversion on each element of line.split(): >>> array = [ [float(j) for j in line.split()] for line in open("/tmp/tfile.txt").readlines() ] >>> array [[20.92060089, -27.72520065, -27.5522995], [-20.92469978, -27.69650078, -27.55340004], [-20.92469978, -27.69890022, -27.55170059]] >>> array[0][0] 20.92060089 >>> type(array[0][0]) <class 'float'>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.