您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:python用字节处理文件实例讲解

51自学网 2021-10-30 22:45:56
  python
这篇教程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', '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'

知识点扩展:

读取文件的字节流数据,将其转换为十六进制数据

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 base64def 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 structa = 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使用字节处理文件的资料请关注51zixue.net其它相关文章!


Python中相见恨晚的技巧(记得收藏)
使用Selenium实现微博爬虫(预登录、展开全文、翻页)
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。