python生成二进制文件_如何使用Python从二进制代码创建PDF文件?

I am trying to send myself PDF files per E-mail with Python. I am able to send myself the binary code of a PDF file, but I am not able to reconstruct the PDF file from this binary code.

Here is how I obtain the binary code of a PDF file:

file = open('code.txt', 'w')

for line in open('somefile.pdf', 'rb').readlines():

file.write(str(line))

file.close()

Here is how I try to create a PDF file from the binary code:

file = open('new.pdf', 'wb')

for line in open('code.txt', 'r').readlines():

file.write(bytes(line))

file.close()

I then recieve this error:

Traceback (most recent call last):

File "something.py", line 3, in

file.write(bytes(line))

TypeError: string argument without an encoding

What did I do wrong?

解决方案

In your first block, open file in binary write mode (wb), since you are writing binary to it. Also, you don't need to convert it explicitly to str. It should look like this:

file = open('code.txt', 'wb')

for line in open('somefile.pdf', 'rb').readlines():

file.write(line)

file.close()

For second block, open file in read binary mode (rb). Here also, no need to explicitly convert to bytes. It should look like this:

file = open('new.pdf', 'wb')

for line in open('code.txt', 'rb').readlines():

file.write(line)

file.close()

This should do the trick. But why do you need to convert it in the first place? Keeping file intact will save your hardwork and computational power.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值