Python Forum
Save list with nested list into CSV
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Save list with nested list into CSV
#1
Question 
Hi everyone,

I would like to save a list (with nested list inside) to a CSV

the problem is that the nested list are quoted with " sign in the csv file.

and when I read back the file the nested list are no longer lists but string :/

any ideas to solve this problem ?
 
import csv

y = [1,10]

data = [
    ['John','Doe',y],
    ['Gordon','Freeman',[5,20]],
    ['Lara','Croft',[7,35]],
]

print(data[0][2]) #give [1,10]
print(len(data[1][2])) #give 2 <------

with open('28_test.csv', 'w', newline='') as output:
    writer = csv.writer(output)
    writer.writerows(data)



readback = []
with open('28_test.csv', 'r') as readed:
    reader = csv.reader(readed)
    readback = list(reader)

print('data:',data)
print('readback:',readback)
print(readback[0][2]) #give [1,10]
print(len(readback[1][2])) #give 7 <------
Reply
#2
CSVs are simple.  There's no (standard) way to store complex data structures with them like lists.   You could create your own protocol to do so, but it wouldn't be understood by other CSV parsers.
  • Save in some other file format (JSON, YAML, etc.)
  • If you only have one, put the nested list at the end (and starting at a particular column).  After you read in the CSV, combine all the columns after that point into a single list via a comprehension.
SpongeB0B likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What is a faster way to deep copy a nested list without using .deepcopy()? Shervin_Ataeian 1 1,506 Oct-13-2024, 01:28 PM
Last Post: Pedroski55
  Strange behavior list of list mmhmjanssen 3 1,631 May-09-2024, 11:32 AM
Last Post: mmhmjanssen
  how to save to multiple locations during save cubangt 1 1,329 Oct-23-2023, 10:16 PM
Last Post: deanhystad
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 2,649 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 3,398 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 1,795 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Сheck if an element from a list is in another list that contains a namedtuple elnk 8 3,473 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 2,643 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Split a number to list and list sum must be number sunny9495 5 3,856 Apr-28-2022, 09:32 AM
Last Post: Dexty
  Updating nested dict list keys tbaror 2 1,950 Feb-09-2022, 09:37 AM
Last Post: tbaror

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020