-3

I have a txt file as following:

12 13 14 15
78 79 80 90
45 63 29 78

I want to convert it into a list of lists so as to have:

[[12,13,14,15],[78,79,80,90],[45,63,29,78]]
stud_eco
  • 123
  • 7
  • 1
    How about the use of `numpy`? https://stackoverflow.com/questions/6081008/dump-a-numpy-array-into-a-csv-file – SKPS Feb 12 '20 at 18:22
  • 2
    To clarify, are you trying to convert to a CSV, or a python list of lists? – Hal Jarrett Feb 12 '20 at 18:23
  • In reality I thought I needed to convert it into a csv file to do so but I actually need to convert it into a list of lists @HalJarrett – stud_eco Feb 12 '20 at 18:29
  • @stud_eco You should edit your question to reflect that, then. – AMC Feb 12 '20 at 19:24
  • With that out of the way, can you clarify what the issue is? There are plenty of resources on the subject already. – AMC Feb 12 '20 at 19:25
  • I think this is now a duplicate of https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python?noredirect=1&lq=1. – AMC Feb 12 '20 at 19:27

1 Answers1

2
import csv

# read the data (space delimited)
with open('data.txt',newline='') as f:
    data = list(csv.reader(f,delimiter=' '))

# data is list of lists, but strings
print(data)

# convert to integers if needed
ints = [[int(n) for n in row] for row in data]
print(ints)

# write back out as true CSV
with open('data.csv','w',newline='') as f:
    csv.writer(f).writerows(data) # data or ints will write correctly.

Output:

[['12', '13', '14', '15'], ['78', '79', '80', '90'], ['45', '63', '29', '78']]
[[12, 13, 14, 15], [78, 79, 80, 90], [45, 63, 29, 78]]

data.csv:

12,13,14,15
78,79,80,90
45,63,29,78
Mark Tolonen
  • 132,868
  • 21
  • 152
  • 208
  • I get IOPub data rate exceeded. The notebook server will temporarily stop sending output to the client in order to avoid crashing it. To change this limit, set the config variable `--NotebookApp.iopub_data_rate_limit`. Current values: NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec) NotebookApp.rate_limit_window=3.0 (secs) – stud_eco Feb 12 '20 at 18:33
  • @stud_eco That's fine, it just means you're printing to stdout too much. – AMC Feb 12 '20 at 19:25