Python3错误解码ascii符号(Python2.7工作正常)

2024-05-19 23:03:10 发布

您现在位置:Python中文网/ 问答频道 /正文

通过httpapi,我得到整数数组,[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文件已损坏,无法读取

有什么问题吗?你知道吗

编辑:

用Python2.7试过了,文件打开了,很好。问题没有解决,我需要在python3.6中使用它

编辑: https://stackoverflow.com/a/25839524/7451009-这个解决方案没问题!你知道吗


Tags: 文件pathjsonhttpurl编辑mapdata
1条回答
网友
1楼 · 发布于 2024-05-19 23:03:10

当它在Python2而不是Python3中工作时,提示可能是由字节vs 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)

相关问题 更多 >