如何使用Python从二进制代码创建PDF文件? [英] How do I create a PDF file from a binary code using Python?

查看:829
本文介绍了如何使用Python从二进制代码创建PDF文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python通过电子邮件向自己发送PDF文件.我可以向自己发送PDF文件的二进制代码,但无法从该二进制代码重建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.

这是我获取PDF文件的二进制代码的方式:

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()

这是我尝试通过二进制代码创建PDF文件的方法:

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()

然后我收到此错误:

回溯(最近通话最近): 在第3行的文件"something.py"中 file.write(bytes(line)) TypeError:不带编码的字符串参数

Traceback (most recent call last): File "something.py", line 3, in file.write(bytes(line)) TypeError: string argument without an encoding

我做错了什么?

推荐答案

在第一个块中,因为要向其中写入二进制文件,所以以二进制写入模式(wb)打开文件.另外,您不需要将其显式转换为str.它应该看起来像这样:

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()

对于第二个块,以读取二进制模式(rb)打开文件.同样,这里也无需显式转换为字节.看起来应该像这样:

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.

这篇关于如何使用Python从二进制代码创建PDF文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆