python如何写二进制文件_Python写入二进制文件,字节

如果您的目的只是复制文件,那么可以使用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:

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值