Python:读取文件:防止转义特殊字符

时间:2017-10-08 17:35:13

标签: python special-characters

我正在从包含以下内容的文件中读取: this is the first line\n this is the second line\n\nAnother line

我试图阅读此文件并保留特殊字符\n

with open(r'test.txt') as f:
    c = f.read()

但打印c始终显示:

this is the first line\\n this is the second line\\n\\nAnother line

我在[{1}}中没有使用r作为前缀,但它没有改变任何内容。

是否可以防止转义特殊字符r'text.txt'

我当然可以做\n,但我只是想知道如果没有这个额外的步骤我们是否可以做到。

1 个答案:

答案 0 :(得分:0)

我看到两个场景:

  1. 您正在使用Python 2在文本模式下在Windows上阅读它.Windows正在使用<Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock Text="{x:Bind DisplayName}"/> <WebView Source="{x:Bind UriSource}" Grid.Row="1"/> <Border Grid.RowSpan="2" Background="Transparent"/> </Grid> ,因此文本模式下的Python 2需要\r\n。您应该通过添加\r\nU启用通用换行模式。您也可以使用open('file.txt', 'rU')代替io.open。我没有Python 2,所以我没试过......

  2. 您的文件中确实有两个字符open\,而不是换行符,在这种情况下,所有内容都按预期运行。

相关问题