简体   繁体   中英

Txt file to arrays

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]]

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM