JCF
JCF

Reputation: 309

Write nested lists in a csv file keeping the exact format

I need to store nested lists in a csv file in the exact python format, i.e., [[1,2,3],[4,5,6],[7,8,9]].

I would like to stick to the csv module, so I wrote the simple code below:

import csv

matrix = [[1,2,3],[4,5,6],[7,8,9]]

with open ('matrix.txt','w',newline='') as f:
    content=csv.writer(f)
    content.writerow(matrix)

The code above stores the following in the file: "[1, 2, 4]","[2, 3, 5]","[3, 4, 6]" So, we miss the first and last square brackets and get superfluous quoting on top.

I tried various options with delimiter, quotechar, and quoting options as shown in the documentation, but without success. If converted to a string, it inserts a comma between every char.

How can I store the exact matrix in its original format (i.e., [[1,2,3],[4,5,6], [7,8,9]])?

Upvotes: 1

Views: 626

Answers (1)

teedak8s
teedak8s

Reputation: 780

One of the easiest way if you are only looking to store your list in the file and not rely on csv module altogether would be to use simple file reader and writer provided by python.

See if this helps:

>>> import ast
>>> 
>>> # Step 1: Storage
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> # Storing matrix as string
>>> with open("test.txt","w+") as fp:
...     fp.write(str(matrix))
... 
33
>>> # Reading the file
>>> with open("test.txt","r") as fp:
...     res=fp.read()
...     print(res)
...     print(type(res))
... 
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
<class 'str'>
>>> # Converting string back to list
>>> with open("test.txt","r") as fp:
...     f=fp.read()
...     res=ast.literal_eval(f)
...     print(type(res))
...     print(res)
... 
<class 'list'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Upvotes: 1

Related Questions