You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python脚本将.csv加密为.csv.pgp?PGPy写入报错求助

解决PGPy加密文件后无法保存为.csv.pgp的问题

错误原因

你触发的TypeError: a bytes-like object is required, not 'PGPMessage',是因为pub_key.encrypt()返回的是PGPy封装的PGPMessage对象,而Python文件的write()方法仅接受字节类型数据,无法直接写入PGPMessage对象。

修复方案

有两种简单的方式将PGPMessage转换为可写入文件的字节数据:

方式1:写入ASCII Armored格式(文本编码的PGP消息)

这种格式是PGP的标准文本表示,适合通过文本渠道传输,代码修改如下:

import pgpy
from pgpy import PGPKey, PGPMessage

PUBLIC_KEY_FILE = 'myPublicKey.asc'    
pub_key, _ = pgpy.PGPKey.from_file(str(PUBLIC_KEY_FILE))
FILE_TO_ENCRYPT = 'data.csv'

f_t_e = pgpy.PGPMessage.new(str(FILE_TO_ENCRYPT), file=True)
print(f_t_e.is_encrypted)

encrypted_f_t_e = pub_key.encrypt(f_t_e)
print(encrypted_f_t_e)

with open('data.csv.pgp', 'wb') as encrypted_file:
    # 将PGPMessage转为ASCII字符串,再编码为字节写入
    encrypted_file.write(str(encrypted_f_t_e).encode('utf-8'))

方式2:写入原始二进制格式

如果不需要文本可读性,直接写入二进制格式可以减小文件体积,修改写入部分即可:

with open('data.csv.pgp', 'wb') as encrypted_file:
    # 直接将PGPMessage转为字节对象
    encrypted_file.write(bytes(encrypted_f_t_e))

内容的提问来源于stack exchange,提问作者Aman shaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 12:50:17