I want to write a list of lists to csv file with one script and simply read it again into a list of lists with the same format with another script. Problem is when I read the csv file back, there is apostrophes around each list when printing the entire line, like this:
a = [ [ [1,2,3], [4,5,6], [7,8,9] ],
[ [1,2,3], [4,5,6], [7,8,9] ],
[ [1,2,3], [4,5,6], [7,8,9] ],
[ [1,2,3], [4,5,6], [7,8,9] ],
[ [1,2,3], [4,5,6], [7,8,9] ] ]
path = "enter path here"
print("")
print(a)
print("")
with open(path, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(a)
with open(path, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
rows = list(csv_reader)
print(rows)
Printing list a
looks like this as before writing expected:
[[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]
But reading list rows
back prints this:
[['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]'], ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]'], ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]'], ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]'], ['[1, 2, 3]', '[4, 5, 6]', '[7, 8, 9]']]
But if I print this rows[0]
, there are no apostrophes:
[1, 2, 3]
I think this is caused by the way the list is written to csv as the apostrophes indicate that each inner list element is written to the csv file as a string. How can I get around this so I don’t read back the apostrophes? Or is there a simple way I can remove them?