Python 从文件读取 vs 直接分配文字

Python reading from file vs directly assigning literal

asked a Python question minutes ago 关于 Python 的换行如何工作只是因为另一个问题甚至不相似或与 Python 相关联而关闭它。

我在一个文件中有包含 '\n' 字符和 '\t' 的文本。我使用

阅读它
open().read()

然后我将结果存储在一个标识符中。我的期望是这样的文本,例如

I\nlove\tCoding

从文件中读取并分配给标识符应该与直接分配给字符串文字的标识符相同

"I\nlove\tCoding"

直接分配给一个文件。

反正我的假设是错误的

word = I\nlove\tCoding

最终不同于

word = open(*.txt).read()

其中*.txt的内容与字符串“I\nlove\tCoding”完全相同

编辑:

无论如何我确实打错了,我的意思是 \t && \n ,用 re 模块的 search() 搜索 \t,它 return None,但是 \t 在那里。请问这是为什么?

从文件中读取后得到的字符串是 I\nlove\nCoding。如果您希望从文字中得到的字符串等于从文件中得到的字符串,您应该使用 r 前缀。像这样 - word = r"I\nlove\nCoding"

你需要区分newlines/tabs和它们对应的转义序列:

for filename in ('test1.txt', 'test2.txt'):
    print(f"\n{filename} contains:")
    fileData = open(filename, 'r').read()
    print(fileData)

    for pattern in (r'\n', r'\n'):
        # first is the escape sequences, second the (real) newline!
        m = re.search(pattern, fileData)
        if m:
            print(f"found {pattern}")

输出:

test1.txt contains:
I\nlove\tCoding
found \n

test2.txt contains:
I
love    Coding
found \n