我想使用 Python 3.4.2 获取网站的一部分。根据元标记,该网站使用 iso-8859-1 编码。我想将一部分(连同其他部分)写入 CSV 文件。
然而,这部分包含一个未定义的字符,其十六进制值为 0x8b。为了尽可能好地保留该部分,我想将其原样写入 CSV 文件中。但是,Python 不允许我这样做。
这是一个最小的例子:
import urllib.request
import urllib.parse
import csv
if __name__ == "__main__":
with open("bytewrite.csv", "w", newline="") as csvfile:
a = b'\x8b' # byte literal by urllib.request
b = a.decode("iso-8859-1")
w = csv.writer(csvfile)
w.writerow([b])
这是输出:
Traceback (most recent call last):
File "D:\Eigene\Dateien\Code\Python\writebyte.py", line 12, in <module>
w.writerow([b])
File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x8b' in position 0: character maps to <undefined>
最终,我手动完成了。它只是用 Notepad++ 复制和粘贴,根据十六进制编辑器,值被正确插入。但是我怎样才能用 Python 3 做到这一点呢?为什么 Python 甚至关心 0x8b 代表什么,而不仅仅是将其写入文件?
根据iso8859_1.py(还有cp1252.py)在C:\Python34\lib\encodings\ 查找表似乎没有干扰:
# iso8859_1.py
'\x8b' # 0x8B -> <control>
# cp1252.py
'\u2039' # 0x8B -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
请您参考如下方法:
引自csv文档:
Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.
发生的事情是您已经从 iso-8859-1 解码为 Unicode,但是 getpreferredencoding() 返回 cp1252 和 Unicode该编码不支持字符 \x8b。
更正的最小示例:
import csv
with open('bytewrite.csv', 'w', encoding='iso-8859-1', newline='') as csvfile:
a = b'\x8b'
b = a.decode("iso-8859-1")
w = csv.writer(csvfile)
w.writerow([b])
