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