开发者社区> 问答> 正文

读写字节数据

你想读写二进制文件,比如图片,声音文件等等。

展开
收起
哦哦喔 2020-04-17 12:23:06 1019 0
1 条回答
写回答
取消 提交回答
  • 使用模式为 rb 或 wb 的 open() 函数来读取或写入二进制数据。比如:
    
    # Read the entire file as a single byte string
    with open('somefile.bin', 'rb') as f:
        data = f.read()
    
    # Write binary data to a file
    with open('somefile.bin', 'wb') as f:
        f.write(b'Hello World')
    在读取二进制数据时,需要指明的是所有返回的数据都是字节字符串格式的,而不是文本字符串。 类似的,在写入的时候,必须保证参数是以字节形式对外暴露数据的对象(比如字节字符串,字节数组对象等)。
    
    2020-04-17 12:23:15
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载