Sự khác biệt giữa bytes[]
và bytearray[]
là bytes[]
trả về một đối tượng không thể sửa đổi và bytearray[]
trả về một đối tượng có thể sửa đổi
Loại byte trong Python là bất biến và lưu trữ một chuỗi các giá trị nằm trong khoảng từ 0-255 [8 bit]. Bạn có thể lấy giá trị của một byte bằng cách sử dụng một chỉ mục giống như một mảng, nhưng không thể sửa đổi các giá trị
# Create empty bytes
empty_bytes = bytes[4]
print[type[empty_bytes]]
print[empty_bytes]
Loại Bytearray
Để tạo một đối tượng có thể thay đổi, bạn cần sử dụng loại bytearray. Với một mảng phụ, bạn có thể làm mọi thứ có thể với các biến khác như đẩy, bật, chèn, nối, xóa và sắp xếp
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
Lớp BytesIO
Kế thừa từ io. Lớp BufferedReader đi kèm với các hàm như read[], write[], peek[], getvalue[]. Nó là một bộ đệm byte chung mà bạn có thể làm việc với
binary_stream = io.BytesIO[]
# Binary data and strings are different types, so a str
# must be encoded to binary using ascii, utf-8, or other.
binary_stream.write["Hello, world!\n".encode['ascii']]
binary_stream.write["Hello, world!\n".encode['utf-8']]
# Move cursor back to the beginning of the buffer
binary_stream.seek[0]
# Read all data from the buffer
stream_data = binary_stream.read[]
# The stream_data is type 'bytes', immutable
print[type[stream_data]]
print[stream_data]
# To modify the actual contents of the existing buffer
# use getbuffer[] to get an object you can modify.
# Modifying this object updates the underlying BytesIO buffer
mutable_buffer = binary_stream.getbuffer[]
print[type[mutable_buffer]] # class 'memoryview'
mutable_buffer[0] = 0xFF
# Re-read the original stream. Contents will be modified
# because we modified the mutable buffer
binary_stream.seek[0]
print[binary_stream.read[]]
Ghi byte vào tệp
# Pass "wb" to write a new file, or "ab" to append
with open["test.txt", "wb"] as binary_file:
# Write text or bytes to the file
binary_file.write["Write text by encoding\n".encode['utf8']]
num_bytes_written = binary_file.write[b'\xDE\xAD\xBE\xEF']
print["Wrote %d bytes." % num_bytes_written]
Ngoài ra, bạn có thể gọi open và close một cách rõ ràng, nhưng nếu bạn làm theo cách này, bạn sẽ phải tự xử lý lỗi và đảm bảo tệp luôn được đóng, ngay cả khi có lỗi trong khi viết. Tôi không khuyến nghị phương pháp này trừ khi bạn có lý do chính đáng
binary_file = open["test.txt", "wb"]
binary_file.write[b'\x00']
binary_file.close[]
Đọc byte từ một tệp
with open["test_file.dat", "rb"] as binary_file:
# Read the whole file at once
data = binary_file.read[]
print[data]
Đọc từng dòng tệp
Nếu bạn đang làm việc với tệp văn bản, bạn có thể đọc dữ liệu theo từng dòng
with open["test.txt", "rb"] as text_file:
# One option is to call readline[] explicitly
# single_line = text_file.readline[]
# It is easier to use a for loop to iterate each line
for line in text_file:
print[line]
Lấy kích thước của một tập tin
import os
file_length_in_bytes = os.path.getsize["test.txt"]
print[file_length_in_bytes]
Tìm kiếm một vị trí cụ thể trong một tập tin
Bạn có thể di chuyển đến một vị trí cụ thể trong tệp trước khi đọc hoặc ghi bằng seek[]. Bạn có thể chuyển một tham số duy nhất tới seek[] và nó sẽ di chuyển đến vị trí đó, so với phần đầu của tệp
________số 8_______Số nguyên sang Byte
i = 16
# Create one byte from the integer 16
single_byte = i.to_bytes[1, byteorder='big', signed=True]
print[single_byte]
# Create four bytes from the integer
four_bytes = i.to_bytes[4, byteorder='big', signed=True]
print[four_bytes]
# Compare the difference to little endian
print[i.to_bytes[4, byteorder='little', signed=True]]
# Create bytes from a list of integers with values from 0-255
bytes_from_list = bytes[[255, 254, 253, 252]]
print[bytes_from_list]
# Create a byte from a base 2 integer
one_byte = int['11110000', 2]
print[one_byte]
# Print out binary string [e.g. 0b010010]
print[bin[22]]
Byte sang Số nguyên
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
0Mã hóa văn bản
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
1# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
2Mã hóa cơ sở 64
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
3thập lục phân
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
4định dạng chuỗi
Các chuỗi định dạng có thể hữu ích để trực quan hóa hoặc xuất các giá trị byte. Các chuỗi định dạng yêu cầu một giá trị số nguyên nên byte sẽ phải được chuyển đổi thành một số nguyên trước
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
5Hoạt động theo bit
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
6Cấu trúc đóng gói và giải nén
Đóng gói và giải nén yêu cầu một chuỗi xác định cách dữ liệu nhị phân được cấu trúc. Nó cần biết byte nào đại diện cho giá trị. Nó cần biết liệu toàn bộ bộ byte đặt lại các ký tự hay nếu nó là một chuỗi các số nguyên 4 byte. Nó có thể được cấu trúc theo nhiều cách. Chuỗi định dạng có thể đơn giản hoặc phức tạp. Trong ví dụ này, tôi đang đóng gói một số nguyên bốn byte theo sau là hai ký tự. Các chữ cái i và c đại diện cho số nguyên và ký tự
# Cast bytes to bytearray
mutable_bytes = bytearray[b'\x00\x0F']
# Bytearray allows modification
mutable_bytes[0] = 255
mutable_bytes.append[255]
print[mutable_bytes]
# Cast bytearray back to bytes
immutable_bytes = bytes[mutable_bytes]
print[immutable_bytes]
7Thứ tự byte hệ thống
Bạn có thể cần biết thứ tự byte mà hệ thống của bạn sử dụng. Thứ tự byte đề cập đến endian lớn hoặc endian nhỏ. Mô-đun sys có thể cung cấp giá trị đó