Python pandas dataframe write \n as text to csv file

Viewed 29

What I would like is to write the sentence "hello \n world\n." in a cell as it is, without "\n" being considered end of line, such that when I open it in a text editor I could see exactly "hello \n world\n.". How can I do that?

2 Answers

In Python backslash is used as escape character. This means that inside string if you dont want to use special character such as newline character, you have put the backslash in front.

print("Hello \nWorld")
-> Hello
   World

print("Hello \\nWorld")
-> Hello \nWorld

Use this way:

import pandas as pd
df = pd.DataFrame({'full_string':['hello \n world! \n', 'hello \nworld!\n']})


df = df.stack().str.replace('\n', '\\n', regex=True).unstack()


df.to_csv('hi.csv')

Output text:

,full_string
0,hello \n world! \n
1,hello \nworld!\n
Related