I have a list: ['1','2','3'] and want to convert it to 1,2,3 i.e. no brackets or quotation marks.
6 Answers
",".join(lst)
will do it, but that's not really csv (would need escaping and such).
If you want to generate 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'])
-
Sure. It's added to the answer. Just use
foo.writerow(list)
, wherefoo
is yourcsv.writer
object.– asthasrJan 7, 2011 at 3:27 -
1IMHO a "canonical" CSV would use comma as a delimiter, not
' '
, and probably'"'
as the quotechar, not'|'
. Jan 7, 2011 at 6:02 -
You can convert almost any list to csv using pandas like this:
import pandas as pd
list1 = [1,2,3,4,5]
df = pd.DataFrame(list1)
Depending on what you want to do with this csv, you can either keep the csv in a variable:
csv_data = df.to_csv(index=False)
Or save it in your filesystem like this:
df.to_csv('filename.csv', index=False)
Here index=False
will remove unnecessary indexing/numbering in your csv.
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)
-
Why do you have the
'b'
(binary mode) mode for the fileopen
? Jun 30, 2020 at 23:31
I think you need to split out the file opening part of your code so that you can close that later, separately. In this case, you are trying to "close" the writer object. Although the better way is to use "with", this example is more similar to the way you have it:
csvfile = open('test.csv', 'wb')
csvwriter = csv.writer(csvfile)
for item in pct:
csvwriter.writerow(item)
csvfile.close()
Carl, whenever you write data into a file what Python actually does is buffer the data and then does its I/O operation with the file (writing the data into the file). This operation is called 'flushing' (the buffers). You have to make sure you are close()ing the opened file, if not, buffer won't be flushed and thus you won't have anything written in the file.