Write text with comma into a cell in CSV file using python

前端 未结 3 710
刺人心
刺人心 2020-12-03 17:48

I want to write text with comma into a cell in CSV file.

Input

\'1,2,3,Hello\'

Output in CSV should be

\'1,2,3\',\'Hello\

3条回答
  •  半阙折子戏
    2020-12-03 18:44

    This is not Python specific, but is to do with the CSV "standard".

    If you want to write a control character as part of your value, you'll need to escape the value by surrounding it in double-quotes:

    f.write('1,2,3,45,"The Next comma I want to write and not separate to another cell, so this sentence will be whole",6,7,8')
    

    Edit: Although in practice, it will be a better idea to use the CSV writer interfaces as suggested by others. It's never a good idea to embroil yourself in the implementation details when there's a ready-rolled library that abstracts this away for you.

提交回复
热议问题