Writing to CSV, getting “Error: need to escape” for a blank string

The issue is most probably occuring because your description has | in it, which is the delimiter for your csv as well. Hence, csv is trying to escape it, but cannot since no csv.escapechars are set. Example to show same issue in my computer –

>>> description = 'asda|sd'
>>> formatted_numbers=""
>>> with open('a.csv','w') as f:
...     writer = csv.writer(f, quoting=csv.QUOTE_NONE, delimiter="|", quotechar="")
...     writer.writerow([
...             description,
...             formatted_numbers
...             ])
...
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
_csv.Error: need to escape, but no escapechar set

One fix would be to provide an escapechar so that it can be escaped. Example –

writer = csv.writer(f, quoting=csv.QUOTE_NONE, delimiter="|", quotechar="",escapechar="\\")    #Or any other appropriate escapechar

Or another fix would be to remove the | in the description before trying to write it, if you do not really need it in the description field –

description = description.replace('|','')

Or you can quote all the fields , by using csv.QUOTE_ALL instead of csv.QUOTE_NONE as provide a valid quotechar .

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)