DennisLi
DennisLi

Reputation: 4154

Python csv dictwriter how to avoid writing multiple lines if data itself contain line break?

For instance, one of the cell is like this, there is line break inside the data.

           +- 'Join LeftOuter, ('A.CARD_CODE = 'C.CARD_CODE)
               :- 'Join LeftOuter, ('A.SCENE_CODE = 'B.SCENE_CODE)
               :  :- 'SubqueryAlias `A`
               :  :  +- 'Aggregate ['SCENE_CODE, 'CARD_CODE, 'PRT_DT]

The problem is the output csv will be separated to several lines if the above data happens.

How can I make them only one line?

The snippet:

with open('general_result.csv', 'a') as f:
  writer = csv.DictWriter(f, result_done.keys(), delimiter='|')
  writer.writerow(result_done)

Upvotes: 1

Views: 111

Answers (1)

AKX
AKX

Reputation: 169328

You'll have to preprocess your data so there are no newlines within strings, e.g. by replacing them with a marker:

with open('general_result.csv', 'a') as f:
  writer = csv.DictWriter(f, result_done.keys(), delimiter='|')
  result_without_newlines = {
    k: str(v).replace('\n', '<NL>')
    for k, v
    in result_done.items()
  }
  writer.writerow(result_done)

Upvotes: 1

Related Questions