我想知道如何以特殊字符不会覆盖我的.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打开文件时,默认编码为ANSI,它将不支持这些特殊字符。因此,您需要将编码更改为utf-8
。为此,只需将代码更改为此: