以未知编码写入数据



是否可以将数据写入未知编码的文件?我无法解码电子邮件头,例如message-id,因为如果我使用处理程序忽略或替换https://docs.python.org/3/library/codecs.html#error-handlers非rfc标头将符合rfc标准,反垃圾邮件不会增加垃圾邮件得分。

我得到字符串从后缀在毫米协议。我不能保存此数据不变的反垃圾邮件,引发UnicodeError。例子:

猫savefile

#!/usr/bin/python3
import sys
fh = open('test', 'w+')
fh.write(sys.argv[1])
echo žlutý | xargs ./savefile && cat test
žlutý
echo žlutý | iconv -f UTF-8 -t ISO8859-2 - | xargs ./savefile 
Traceback (most recent call last):
File "/root/./savefile", line 5, in <module>
fh.write(sys.argv[1])
UnicodeEncodeError: 'utf-8' codec can't encode character 'udcbe' in position 0: surrogates not allowed

输入可能是很多未知的编码。

您想要处理原始bytes,而不是字符串。open以二进制方式输出文件。注意:

sys.argv

.

注意:在Unix上,命令行参数以字节为单位从操作系统传递。Python使用文件系统编码和" surrogateescape "错误处理程序对它们进行解码。当您需要原始字节时,您可以通过[os.fsencode(arg) for arg in sys.argv]获取。

<子>https://docs.python.org/3/library/sys.html sys.argv

:

import sys
import os
with open('test', 'wb+') as fh:
fh.write(os.fsencode(sys.argv[1]))

最新更新