How to prevent a nested list from being parsed as a string by Python's csv.reader?

Viewed 137

I have a nested list, like so:

[[['Mario', 100], ['Luigi', 100]], [['Donatello', 200]]]

Which I am trying to save to a CSV file like so:

import csv

with open('myfile.csv', 'w', newline='') as file:
    csv_writer = csv.writer(file, delimiter=';')

    for row in mylist:
        csv_writer.writerow(row)

And then I read it like so:

with open('myfile.csv', 'r') as file:
    csv_reader = csv.reader(file, delimiter=';')

    for row in csv_reader:
        list_to_return.append(row)

return list_to_return

When I check myfile.csv, it looks like this:

['Mario', 100];['Luigi', 100]
['Donatello', 200]

However, when I read from myfile.csv, the list looks like this:

[["['Mario', 100]", "['Luigi', 100]"], ["['Donatello', 200]"]]

In other words, it seems the innermost list is parsed by the CSV reader as a string, and not a list.

I was wondering if any of you could help me with this. Why is the nested Python list parsed as a string by the CSV reader?

1 Answers

Use Numpy as given here Code:

import numpy as np

a = np.array([[['Mario', 100], ['Luigi', 100]], [['Donatello', 200]]])
print(a)

np.savez_compressed('myfile.npz', a=a)

arr_read = np.load('myfile.npz', allow_pickle=True)
arr_from_file = arr_read['a']
print(arr_from_file)

Output:

[list([['Mario', 100], ['Luigi', 100]]) list([['Donatello', 200]])]
[list([['Mario', 100], ['Luigi', 100]]) list([['Donatello', 200]])]
Related