1. You can add the 'b' character to the mode parameter. All the same methods suitable for file objects. However, each method expects and returns a bytes object.
>>> with open(`dog_breeds.txt`, 'rb') as reader: >>> print(()) b'Pug\n'
2. When opening the file and reading the bytes individually, you can see that it is indeed a png file:.
>>> 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'
Knowledge Point Expansion:
Reads byte stream data from a file and converts it to hexadecimal data
def read_file(): with open('./','rb') as file_byte: file_hex = file_byte.read().hex() print(file_hex) write_file(file_hex) def write_file(file_hex): with open('','w') as new_file: new_file.write(file_hex) if __name__ == '__main__': read_file()
Reads the byte stream data of a file, encodes it as base64 and outputs it
import base64 def read_file(): with open('./','rb') as file_byte: file_base64 = base64.b64encode(file_byte.read()) print(file_base64) if __name__ == '__main__': read_file()
Write hexadecimal files to byte stream files
import struct a = open("","r")# Hexadecimal data files lines = () res = [lines[i:i+2] for i in range(0,len(lines),2)] with open("","wb") as f: for i in res: s = ('B',int(i,16)) (s)
The above is python using bytes to deal with files examples to explain the details, more information about python using bytes to deal with files please pay attention to my other related articles!