时间:2021-05-23
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使用字节处理文件的资料请关注其它相关文章!
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
SpringMVC的文件下载实例详解读取文件要下载文件,首先是将文件内容读取进来,使用字节数组存储起来,这里使用spring里面的工具类实现importorg.
复制文件的三种方法:1、Files.copy(path,newFileOutputStream(dest));。2、利用字节流。3、利用字符流。代码实现如下:p
计算机储存和处理数据的基本单位是字节。字节是计算机数据处理的基本单位。1个字节由8个二进制位组成,常用B表示。在计算机和其他的数字设备中,一般用字节作为存储容量
本文实例讲述了python异常和文件处理机制。分享给大家供大家参考,具体如下:1异常处理Python的异常用tryexceptfinally来处理.并且exce
以下实例我们使用phpcurl来获取远程文件大小,返回文件大小单位为字节:以上实例输出结果为:8416字节