Python 3 - 不正确解码 ascii 符号(Python 2.7 运行良好)
Python 3 - incorrect decoding ascii symbols (Python 2.7 works well)
通过 HTTP API 我得到整数数组,[37,80,68,70,45] - 等等,代表 ascii 码。我需要将其另存为pdf文件。 php 中的代码是:
$data = file_get_contents($url);
$pdf_data = implode('', array_map('chr', json_decode($data)));
file_put_contents($file_path.".pdf", $pdf_data);
而且效果很好。
但是,在 python 3:
http_request_data = urllib.request.urlopen(url).read()
data = json.loads(http_request_data)
pdf_data = ''.join(map(chr, data))
with open(file_path, 'w') as fout:
fout.write(pdf_data)
结果pdf文件损坏,无法读取
可能是什么问题?
编辑:
尝试使用 python 2.7,文件打开并且很好。问题没有解决,我需要在python 3.6
编辑:
- 这个解决方案没问题!
当它在 Python2 中工作而不在 Python3 中工作时,提示它可能是由字节与 unicode 问题引起的。
字符串和字符在 Python2 中是字节,在 Python3 中是 unicode。如果您的代码在 Python2 中有效,则其 Python3 等效项应为:
http_request_data = urllib.request.urlopen(url).read()
data = json.loads(http_request_data)
pdf_data = bytes(data) # construct a bytes string
with open(file_path, 'wb') as fout: # file must be opened in binary mode
fout.write(pdf_data)
通过 HTTP API 我得到整数数组,[37,80,68,70,45] - 等等,代表 ascii 码。我需要将其另存为pdf文件。 php 中的代码是:
$data = file_get_contents($url);
$pdf_data = implode('', array_map('chr', json_decode($data)));
file_put_contents($file_path.".pdf", $pdf_data);
而且效果很好。
但是,在 python 3:
http_request_data = urllib.request.urlopen(url).read()
data = json.loads(http_request_data)
pdf_data = ''.join(map(chr, data))
with open(file_path, 'w') as fout:
fout.write(pdf_data)
结果pdf文件损坏,无法读取
可能是什么问题?
编辑:
尝试使用 python 2.7,文件打开并且很好。问题没有解决,我需要在python 3.6
编辑: - 这个解决方案没问题!
当它在 Python2 中工作而不在 Python3 中工作时,提示它可能是由字节与 unicode 问题引起的。
字符串和字符在 Python2 中是字节,在 Python3 中是 unicode。如果您的代码在 Python2 中有效,则其 Python3 等效项应为:
http_request_data = urllib.request.urlopen(url).read()
data = json.loads(http_request_data)
pdf_data = bytes(data) # construct a bytes string
with open(file_path, 'wb') as fout: # file must be opened in binary mode
fout.write(pdf_data)