假设使用Python 2.7.1(即您引用的文档):没有记录“ wt”模式(记录的唯一模式是“ r”),并且不起作用-编解码器模块将“
b”附加到该模式,这导致它失败:
>>> f = precs.open('bar.txt', 'wt', encoding='utf8')Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:python27libprecs.py", line 881, in open file = __builtin__.open(filename, mode, buffering)ValueError: Invalid mode ('wtb')避免编解码器模块和DIY:
f = open('bar.text', 'w')f.write(unipre_object.enpre('utf8'))*关于Python 3.x的 *更新 :
似乎precs.open()具有相同的缺陷(不会编写特定于平台的行终止符)。但是内置有
encodingarg的open()很高兴做到这一点:
[Python 3.2 on Windows 7 Pro]>>> import precs>>> f = precs.open('bar.txt', 'w', encoding='utf8')>>> f.write('line1nline2n')>>> f.close()>>> open('bar.txt', 'rb').read()b'line1nline2n'>>> f = open('bar.txt', 'w', encoding='utf8')>>> f.write('line1nline2n')12>>> f.close()>>> open('bar.txt', 'rb').read()b'line1rnline2rn'>>>*关于Python 2.6的 *更新
文档说的与2.7文档相同。不同之处在于,在2.6中将“ b”附加到模式arg的“大头钉进入二进制模式” hack在2.6中失败,因为未将“
wtb”检测为无效模式,该文件以文本模式打开,并且似乎可以正常工作如您所愿,而不是文件记录:
>>> import precs>>> f = precs.open('fubar.txt', 'wt', encoding='utf8')>>> f.write(u'u0a0aline1nxffline2n')>>> f.close()>>> open('fubar.txt', 'rb').read()'xe0xa8x8aline1rnxc3xbfline2rn' # "works">>> f.mode'wtb' # oops>>>


