通过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
中编辑: https://stackoverflow.com/a/25839524/7451009 - 这个解决方案没问题!
当它在 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)