Home > Net >  How to stop Pandas from saving a csv by breaking lines?
How to stop Pandas from saving a csv by breaking lines?

Time:01-06

The csv output of a tkinter Text widget with line breaks is being saved like this:

"id","comment","name"
1,"ABC",Beth
2,"xyz",Peter
3,"abc
xyz",Mike

enter image description here

I tried to save using lineterminator= both '\r\n' and only '\n' but without success. Some lines I used:

comment = Text(Forms, width=50, height=5 , wrap="word", font=('arial', 10))

df.at[id_q,'comment']=comment.get(1.0, "end-1c")

df.to_csv('./test.csv', encoding='utf-8', index=False, sep = ',' , lineterminator='\r\n')

I wanted the .cvs to look like this using the \n instead of breaking:

"id","comment","name"
1,"ABC",Beth
2,"xyz",Peter
3,"abc\nxyz",Mike

CodePudding user response:

Looks like the issue is that there are line breaks in the cell content, so these will be present in the csv output regardless of the line terminator.

Something like the following should work:

df.at[id_q,'comment']=comment.get(1.0, "end-1c").replace('\n', '').replace('\r', '')

CodePudding user response:

You can use str.decode() and str.encode() to convert the newline to escape string as below:

df.at[id_q,'comment'] = comment.get('1.0', 'end-1c').encode('unicode_escape').decode()

Note that it is for Python 3.

  • Related