如果您的意图是简单地制作文件的副本,您可以使用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
对于 Python 2.7+ 或 3.1+,您还可以使用此快捷方式(而不是使用两个with
块):
with open('/tmp/fin.pdf','rb') as f1,open('/tmp/test.pdf','wb') as f2:
...