How do I create a PDF file from a binary code using Python?

前端 未结 1 1928
慢半拍i
慢半拍i 2021-01-16 14:22

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

相关标签:
1条回答
  • 2021-01-16 14:45

    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)
提交回复
热议问题