Python writing binary files, bytes -


python 3. i'm using qt's file dialog widget save pdfs downloaded internet. i've been reading file using 'open', , attempting write using file dialog widget. however, i've been running a"typeerror: '_io.bufferedreader' not support buffer interface" error.

example code:

with open('file_to_read.pdf', 'rb') f1:      open('file_to_save.pdf', 'wb') f2:         f2.write(f1) 

this logic works text files when not using 'b' designator, or when reading file web, urllib or requests. these of 'bytes' type, think need opening file as. instead, it's opening buffered reader. tried bytes(f1), "typeerror: 'bytes' object cannot interpreted integer." ideaas?

if intent make copy of file, use shutil

>>> import shutil >>> shutil.copyfile('file_to_read.pdf','file_to_save.pdf') 

or if need access byte byte, similar structure, works:

>>> open('/tmp/fin.pdf','rb') f1: ...    open('/tmp/test.pdf','wb') f2: ...       while true: ...          b=f1.read(1) ...          if b:  ...             # process b if intent    ...             n=f2.write(b) ...          else: break 

but byte byte potentially really slow.

or, if want buffer speed (without taking risk of reading unknown file size memory):

>>> open('/tmp/fin.pdf','rb') f1: ...    open('/tmp/test.pdf','wb') f2: ...       while true: ...          buf=f1.read(1024) ...          if buf:  ...              byte in buf: ...                 pass    # process bytes if want ...                         # make sure changes in buf ...              n=f2.write(buf) ...          else: ...              break 

with python 2.7+ or 3.1+ can use shortcut (rather using 2 with blocks):

with open('/tmp/fin.pdf','rb') f1,open('/tmp/test.pdf','wb') f2:     ... 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -