您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

使用Python 2.7+或3.1+,您还可以使用此快捷方式(而不是使用两个with块):

with open('/tmp/fin.pdf','rb') as f1,open('/tmp/test.pdf','wb') as f2:
    ...
python 2022/1/1 18:36:00 有231人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶