如果您只是想复制文件,则可以使用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: ...


