Python从文件读取与直接分配文本

2024-09-30 22:10:09 发布

您现在位置:Python中文网/ 问答频道 /正文

asked a Python question minutes ago关于Python的新行是如何工作的,但却因为另一个问题而关闭了它,这个问题甚至与Python不相似,或者Python与之关联

我在文件中有一个带有'\n'字符和'\t'的文本。我用英语读它

open().read()

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

I\nlove\tCoding

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

"I\nlove\tCoding"

直接分配给文件的

无论如何,我的假设是错误的

word = I\nlove\tCoding

最终与其他人不同

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

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

编辑:

不管怎样,我确实打错了,我的意思是\t&&\n,使用re模块的search()搜索\t,返回None,但\t在那里。这是为什么


Tags: 文件字符串txtread标识符openago字符
2条回答

您需要区分换行符/制表符及其对应的转义序列:

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

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

相关问题 更多 >