如何让Pandas保存CSV时将字段内换行转为\n而非实际换行?
解决Tkinter Text组件内容存入CSV时字段被拆分的问题
当你把Tkinter Text组件里带换行的内容保存成CSV时,会出现字段被拆分的情况,比如生成的CSV里第三行的comment字段直接换行了,破坏了CSV格式:
"id","comment","name" 1,"ABC",Beth 2,"xyz",Peter 3,"abc xyz",Mike
你尝试修改lineterminator参数为'\r\n'或'\n'都没用,用到的代码是:
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')
你期望的是把字段内的换行转成\n字符串,让CSV格式保持正常,像这样:
"id","comment","name" 1,"ABC",Beth 2,"xyz",Peter 3,"abc\nxyz",Mike
解决方法
问题出在Text组件获取的内容里包含实际换行符(\n),写入CSV时,这个换行符会被当成行分隔符。要解决这个问题,只需要在获取Text内容后,把里面的换行符替换成字符串形式的"\n"(也就是转义后的换行标识)。
修改后的代码如下:
comment = Text(Forms, width=50, height=5 , wrap="word", font=('arial', 10)) # 获取内容并替换换行符为"\n"字符串 comment_content = comment.get(1.0, "end-1c").replace('\n', '\\n') df.at[id_q,'comment'] = comment_content df.to_csv('./test.csv', encoding='utf-8', index=False, sep = ',' , lineterminator='\r\n')
说明
replace('\n', '\\n'):这里把实际的换行符(\n)替换成了字符串\n(Python里要表示反斜杠需要转义,所以用\\n),写入CSV后,字段里的换行就会显示为\n而不是实际换行。lineterminator参数控制的是CSV每行之间的分隔符,和字段内的换行无关,不需要改动它。
内容的提问来源于stack exchange,提问作者Silvio Duarte
相关产品推荐
相关产品推荐

