From list of bytes to PDF file

I am working on a simple program that works on PDF files. So far I’ve been able to read the PDF into a list of bytes with the following code:

def bstr(n): # n in range 0-255
    return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])
def read_binary():
    f = open('source.pdf','rb')
    binlist = [ ]
    while True:
        bin = struct.unpack('B',[0] 
        if not bin:
        strBin = bstr(bin)
    return binlist

After manipulating the list of bytes, I would like to get back the PDF file. Is there any way I can reconstruct the PDF file starting from the list of bytes?

(This is a question for the #users channel, as it doesn’t relate to the development of CPython. A moderator will move it soon enough, I’m sure.)

Given how complex you’ve made reading bytes from a file (which is the most basic operation possible), I’d suggest you read a guide on reading/writing files, such as Reading and Writing Files in Python (Guide) – Real Python That’s likely to lead you to a simpler design, as well as helping answer your question about writing to files.

1 Like