<p>Along the lines of my previous <a href="https://stackoverflow.com/questions/118096/how-can-i-parse-a-comma-delimited-string-into-a-list-caveat">question</a>, how can i join a list of strings into a string such that values get quoted cleanly. Something like:</p>

<pre><code>['a', 'one "two" three', 'foo, bar', """both"'"""]
</code></pre>

<p>into:</p>

<pre><code>a, 'one "two" three', "foo, bar", "both\"'"
</code></pre>

<p>I suspect that the csv module will come into play here, but i'm not sure how to get the output I want.</p>

Using the
```
csv
```
module you can do that way:
```
```
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)
```
```
If you need a string just use
```
StringIO
```
instance as a file:
```
```
f = StringIO.StringIO()
writer = csv.writer(f)
writer.writerow(the_list)
print f.getvalue()
```
```
The output:
```
a,"one ""two"" three","foo, bar","both""'"
```
```
csv
```
will write in a way it can read back later.
You can fine-tune its output by defining a
```
dialect
```
, just set
```
quotechar
```
,
```
escapechar
```
, etc, as needed:
```
```
class SomeDialect(csv.excel):
    delimiter = ','
    quotechar = '"'
    escapechar = "\\"
    doublequote = False
    lineterminator = '\n'
    quoting = csv.QUOTE_MINIMAL

f = cStringIO.StringIO()
writer = csv.writer(f, dialect=SomeDialect)
writer.writerow(the_list)
print f.getvalue()
```
```
The output:
```
a,one \"two\" three,"foo, bar",both\"'
```
The same dialect can be used with csv module to read the string back later to a list.