python 读取文本文件 return 奇怪的值

python read text file return strange values

当我读取带有 python 的文本文件时,它 returns 奇怪的值。

例如,我的文件中有以下文本:

a_id

Python读取结果为:

'ÿþa\x00_\x00i\x00d\x00'

python中的open方法默认没有编码。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

这样做:

with open('test.txt') as f:
    print(f.readlines())

将导致:

['þÿ\x00a\x00_\x00i\x00d']

要解决此问题,请添加正确的编码,例如:

with open('test.txt', encoding='utf-16') as f:
    print(f.readlines())

这会给你:

['a_id']