2

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

tripleee
  • 175,061
  • 34
  • 275
  • 318
user3093845
  • 43
  • 13
  • *"i tried for exception block faced some issue with indentation"* looks like English words, but doesn't really make sense. Can you try to rearticulate what you are trying to say here? – tripleee Dec 21 '20 at 05:57
  • As an aside, the recommended naming convention for local variables in Python is `snake_case` instead of `dromedaryCase`; i.e. `input_file`, `output_file`, `each_row` (or in these cases probably just drop the underscore if it pains your eyes). – tripleee Dec 21 '20 at 06:01

1 Answers1

1

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).

tripleee
  • 175,061
  • 34
  • 275
  • 318