• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python用字节处理文件实例讲解

python 搞代码 4年前 (2022-01-07) 27次浏览 已收录 0个评论

在本篇文章里小编给大家整理的是一篇关于python用字节处理文件实例讲解内容,有兴趣的朋友们可以学习参考下。

1、可以在mode参数中添加’b’字符。所有适合文件对象的相同方法。然而,每种方法都希望并返回一个bytes对象。

 >>> with open(`dog_breeds.txt`, 'rb') as reader: >>>     print(reader.readline()) b'Pug\n'

2、当打开文件并单独阅读这些字节时,可以看到它确实是一个png文件:

 >>> with open('jack_russell.png-600', 'rb') as byte_reader: >>>     print(byte_reader.read(1)) >>>     print(byte_reader.read(3)) >>>     print(byte_reader.read(2)) >>>     print(byte_reader.read(1)) >>>     print(byte_reader.read(1)) b'\x89' b'PNG' b'\r\n' b'\x1a' b'\n'

知识点扩展:

读取文件的字节流数据,将来源gaodai#ma#com搞*!代#%^码网其转换为十六进制数据

 def read_file(): with open('./flag.zip','rb') as file_byte: file_hex = file_byte.read().hex() print(file_hex) write_file(file_hex) def write_file(file_hex): with open('new.txt','w') as new_file: new_file.write(file_hex) if __name__ == '__main__': read_file()

读取文件的字节流数据,将其编码为base64并输出

 import base64 def read_file(): with open('./flag.zip','rb') as file_byte: file_base64 = base64.b64encode(file_byte.read()) print(file_base64) if __name__ == '__main__': read_file()

将十六进制文件转化为字节流文件写入

 import struct a = open("str.txt","r")#十六进制数据文件 lines = a.read() res = [lines[i:i+2] for i in range(0,len(lines),2)] with open("xxx.xxx","wb") as f: for i in res: s = struct.pack('B',int(i,16)) f.write(s)

以上就是python用字节处理文件实例讲解的详细内容,更多关于python使用字节处理文件的资料请关注gaodaima搞代码网其它相关文章!

以上就是python用字节处理文件实例讲解的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python用字节处理文件实例讲解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址