Generate csv file from matrix (nested lists)

1

I have a 1000x5 matrix, in the format

['1', 'Visa', '4539897685939002', '116', '5/2022\n']

All values within each row are strings and are sorted increasingly by the first index of each row, something like this:

['1', 'Visa', '4539897685939002', '116', '5/2022\n']
['2', 'MasterCard', '5159561932089468', '627', '2/2023\n']

I try to enter the matrix to a csv file, first I got an error that I could not write lists in the file, then I tried to enter the rows in this way

for linea in matriz:
   archivo.write(str(linea))

All right until I open the file.csv, they are all followed, not in the form of a table, so

['1', 'Visa', '4539897685939002', '116', '5/2022\n'],['2', 'MasterCard', '5159561932089468', '627', '2/2023\n']

The 1000 lines are followed. How could I enter the rows in a table, just as a matrix is supposed to be?

    
asked by Iam Gallano 16.08.2018 в 01:28
source

1 answer

0

First, referring to the first error, write if you open the file in text mode requires a string ( str ), so you can not pass a list. Second, it stores that because it is the string representation that returns the __str__ method of a list, string that is also used by print :

>>> l = [1, 2, 3]
>>> str(l)
'[1, 2, 3]'

To generate a csv, you must intersperse your separator between each item in the list that forms a row and get at the end a single string that you can pass to write . In other cases it is advisable to use the module csv and csv.writer :

import csv


matriz = [['1', 'Visa', '4539897685939002', '116', '5/2022'],
          ['2', 'MasterCard', '5159561932089468', '627', '2/2023']]

with open('salida.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',', quotechar='|',
                        quoting=csv.QUOTE_MINIMAL)
    writer.writerows(matriz)

However, in your specific case you have the character of new line included in your last column and that is a problem. csv.writer would generate a valid csv escaping the last column, but this would include \n as part of the data. That forces us to eliminate the line break previously, so in this case I think the simplest thing is that you use str.join to insert the separator that you think you use in your csv:

matriz = [['1', 'Visa', '4539897685939002', '116', '5/2022\n'],
          ['2', 'MasterCard', '5159561932089468', '627', '2/2023\n']]

with open('salida.csv', 'w') as csvfile:
    csvfile.writelines(','.join(row) for row in matriz)

Which should produce a file with the following content:

  

1, Visa, 4539897685939002,116,5 / 2022
  2, MasterCard, 5159561932089468,627.2 / 2023

That if, you must make sure not to produce an invalid or wrong csv because in this case csv.writer does not protect you. For example, make sure that the data does not contain the separator.

    
answered by 16.08.2018 / 01:55
source