使用换行符转义序列读取csv

时间:2019-05-27 13:19:47

标签: python pandas csv

我有一个csv文件,其中包含一些文本。我希望对代码的以下部分进行转义序列的解释(例如\n应该解释为换行符)。 pd.read_csv正在读取这些文本列,而没有将\n解释为换行符,而是字符串中的两个独立字符,即将其另存为'\\''n'

我的csv文件如下所示(第一行带有列名):

text, number
one line\nother line, 12
second text\nwith more words maybe, 13

并用df = pd.read_csv('file.csv')读取。

我尝试将escapechar参数设置为'\',但是它只是从字符串中删除斜杠,而无需对换行符进行任何解释,即第一个字符串变为one linenother line

输出如下:

In[]: df.iloc[0,0]
'one line\\nother line'
In[]: print(df.iloc[0,0])
one line\nother line

我想要的是:

In[]: df.iloc[0,0]
'one line\nother line'
In[]: print(df.iloc[0,0])
one line
other line

如果我显式设置df.iloc[0,0] = 'one line\nother line',则会得到预期的行为,因为这次\ n实际上被解释为换行符。

理想情况下,我会简单地更改pd.read_csv()解释文件的方式,但是其他解决方案也可以。

PS:我问了类似的问题here,但措词不正确,我没有更改问题,而是接受了给定的答案(因为它回答了我所问的问题,但没有回答我想解决的问题) ,并问了这个新问题。

0 个答案:

没有答案