在PC上编码的Python UTF-8,在Mac上编码的UnicodeDecodeError

时间:2016-07-19 08:20:24

标签: python macos encoding utf-8 pc

我编写了一个脚本来在PC上创建文本文件,它使用这些类型的命令来打开和写入它:

newfile = open(r'tweettext.txt','w')

print("\n"+tweet,end=',',file=newfile)

sys.getdefaultencoding()显示'utf-8'编码。但是当我尝试在Mac上用IDLE打开这个文本文件时:

with open('tweettext.txt','r',encoding='utf-8') as f:
    tweetlist = [line.rstrip() for line in f]

我收到了这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2135: invalid start byte

PC有Python 3.5.1,Mac有3.5.2。如何在Mac上打开此文件,以及如何防止将来发生这种情况?

1 个答案:

答案 0 :(得分:1)

sys.getdefaultencoding()仅适用于sys.stdoutsys.stderrsys.stdin

您在没有编码集的情况下打开了打印的文件,因此使用默认的 for files ,这是locale.getpreferredlocale() function返回的任何内容(请参阅open() function documentation编码)。

明确地设置它:

newfile = open(r'tweettext.txt', 'w', encoding='utf8')