如果您的目的只是复制文件,那么可以使用shutil>>> import shutil
>>> shutil.copyfile('file_to_read.pdf','file_to_save.pdf')
或者,如果需要逐字节访问(与结构类似),则可以:>>> with open('/tmp/fin.pdf','rb') as f1:
... with open('/tmp/test.pdf','wb') as f2:
... while True:
... b=f1.read(1)
... if b:
... # process b if this is your intent
... n=f2.write(b)
... else: break
但逐字节可能会非常慢。
或者,如果您想要一个缓冲区来加快速度(而不冒将未知文件大小完全读入内存的风险):>>> with open('/tmp/fin.pdf','rb') as f1:
... with open('/tmp/test.pdf','wb') as f2:
... while True:
... buf=f1.read(1024)
... if buf:
... for byte in buf:
... pass # process the bytes if this is what you want
... # make sure your changes are in buf
... n=f2.write(buf)
... else:
... break
对于Python2.7+或3.1+,也可以使用此快捷方式(而不是使用两个with块):with open('/tmp/fin.pdf','rb') as f1,open('/tmp/test.pdf','wb') as f2:
...