【问题标题】:Python 3 - incorrect decoding ascii symbols (Python 2.7 works well)Python 3 - 错误解码 ascii 符号(Python 2.7 运行良好)
【发布时间】:2018-06-27 15:37:58
【问题描述】:

通过 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 - 这个解决方案没问题!

【问题讨论】:

  • 如果不检查数据本身就很难回答。

标签: python python-3.x pdf ascii chr


【解决方案1】:

当它在 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)

【讨论】:

猜你喜欢
  • 2016-11-28
  • 2019-08-17
  • 2019-06-19
  • 2014-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 2015-02-03
相关资源
最近更新 更多