How to convert list to csv in python

I have a list: ['1', '2', '3'] and I want to convert it to 1,2,3, that is, without brackets or quotation marks.

+4
source share
5 answers

If you want to create a canonical CSV file, use the csv module.


Example from the docs:

>>> import csv >>> spamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=' ', ... quotechar='|', quoting=csv.QUOTE_MINIMAL) >>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans']) >>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) 
+10
source
 ",".join(lst) 

will do this, but it is not really csv (would have to be escaped, etc.).

+6
source
 import csv def writeCsvFile(fname, data, *args, **kwargs): """ @param fname: string, name of file to write @param data: list of list of items Write data to file """ mycsv = csv.writer(open(fname, 'wb'), *args, **kwargs) for row in data: mycsv.writerow(row) mydat = ( ['Name','Age','Grade'], ['Teri', 14, 7], ['John', 8, 2] ) writeCsvFile(r'c:\test.csv', mydat) 
0
source

Carl, whenever you write data to a file, what Python actually does is a data buffer and then performs an I / O operation on the file (writing data to the file). This operation is called flushing (buffers). You have to make sure that you are closed () in the file that opens, if not, the buffer will not be flushed and, therefore, you will not have anything written to the file.

0
source

I think you need to split the opening part of your code file so that you can close it later, separately. In this case, you are trying to "close" the recording object. Although the best way is to use c, this example is more like using it:

 csvfile = open('test.csv', 'wb') csvwriter = csv.writer(csvfile) for item in pct: csvwriter.writerow(item) csvfile.close() 
0
source

Source: https://habr.com/ru/post/1334619/


All Articles