用Python读取.txt文件,避免特殊字符替换文件中的原始字符

问题描述 投票:0回答:1

我想知道如何以特殊字符不会覆盖我的.txt文件中的内容的方式读取.txt文件,以便可以保留原始文件的内容

我正在使用以下代码行:

with open('D:/nap31.txt') as gh:
    line = True
    while line:
        line = gh.readline()

来自nap31.txt文件的示例内容:

Teda Production Site Oranienburg Lehnitzstr. 70 – 98 16515 Oranienburg France packaging

Zene AB Gärtunavägen SE-151 85 Södertälje SWEDEN Testing

打开文件并使用上述代码阅读后,内容变为:

Teda Production Site Oranienburg Lehnitzstr. 70 – 98 16515 Oranienburg France packaging

Zene AB Gärtunavägen SE-151 85 Södertälje SWEDEN Testing

因此–在我的文件中替换'-',同样,其他特殊字符也在替换其他内容。有人可以帮我解决这个问题

python python-3.x unicode utf-8 special-characters
1个回答
0
投票

当您使用Python打开文件时,默认编码为ANSI,它将不支持这些特殊字符。因此,您需要将编码更改为utf-8。为此,只需将代码更改为此:

© www.soinside.com 2019 - 2024. All rights reserved.