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.