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
  Strange behavior list of list mmhmjanssen 2 173 May-01-2024, 07:16 AM
Last Post: Gribouillis
  how to save to multiple locations during save cubangt 1 572 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 1,222 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Delete strings from a list to create a new only number list Dvdscot 8 1,578 May-01-2023, 09:06 PM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 942 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 1,878 Oct-26-2022, 04:03 PM
Last Post: deanhystad
Question Keyword to build list from list of objects? pfdjhfuys 3 1,597 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  Split a number to list and list sum must be number sunny9495 5 2,332 Apr-28-2022, 09:32 AM
Last Post: Dexty
  Updating nested dict list keys tbaror 2 1,299 Feb-09-2022, 09:37 AM
Last Post: tbaror
  Python Program to Find the Total Sum of a Nested List vlearner 8 5,008 Jan-23-2022, 07:20 PM
Last Post: menator01

Forum Jump:

User Panel Messages

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