Some CSV cells are wrapped in "quotes" while others are not

Viewed 91

I am a newbie to Python. I am not able to debug the code. Can someone please guide how to debug?

with open(inputFile, mode='rt') as f:
    reader = csv.reader(f, delimiter=',',  quotechar='"')
    header = next(reader,None)
    rows = sorted(reader, key=operator.itemgetter(1))
with open(outputFile, 'w') as final:    
    writer = csv.writer(final, delimiter=',')
    writer.writerow(header)
    for eachRow in rows:        
        writer.writerow(eachRow)

In some case the output is

"","xxx"

In other cases, I see

,xxx,

I tried for exception block faced some issue with indentation

1 Answers

When you instantiate csv.writer you can tell it what quoting behavior you want. Pass in quoting=csv.QUOTE_ALL to tell it to meticulously quote everything.

    writer = csv.writer(final, delimiter=',', quoting=csv.QUOTE_ALL)

However, this is typically not necessary; any reasonable CSV implementation will allow and expect most fields to be unquoted. The only fields which really need to be quoted are the ones which contain literal double quotes or commas (or more generally speaking, literal instances of the column separator or the quoting character; there are common CSV dialects like TSV etc which use a different delimiter).

Related