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

The*_*Phi 5 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()
Run Code Online (Sandbox Code Playgroud)

但打印c总是显示:

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

我尝试过不加rin前缀r'text.txt',但它没有改变任何东西。

是否可以防止转义特殊字符\n

我当然可以这样做str.replace('\\n','\n'),但我只是想知道我们是否可以不需要这个额外的步骤。

小智 0

我看到两种情况:

  1. 您正在使用 Python 2 在 Windows 上以文本模式阅读它。Windows 正在使用\r\n,因此文本模式下的 Python 2 是期望的\r\nU您应该通过添加,来启用通用换行模式open('file.txt', 'rU')。您也可以使用io.open代替open. 我没有Python 2,所以我没有尝试过......

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