Explanation of python Using Byte Processing File Example
- 2021-10-25 07:36:37
- OfStack
1. You can add the 'b' character to the mode parameter. The same method for all file objects. However, each method expects and returns 1 bytes object.
>>> with open(`dog_breeds.txt`, 'rb') as reader:
>>> print(reader.readline())
b'Pug\n'
2. When you open the file and read these bytes separately, you can see that it is really an 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'
Extension of knowledge points:
Read the byte stream data of the file and convert it into 106-ary data
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()
Read the byte stream data of the file, encode it as base64 and output it
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()
Convert 106-ary file into byte stream file to write
import struct
a = open("str.txt","r")#106 Binary data file
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)
The above is the python byte processing file example explained in detail, more about python byte processing file information please pay attention to other related articles on this site!