Python bytearray and Binary Files
The last part of PCAP objective 5.5. bytes is immutable and bytearray is its mutable sibling - a sequence of integers 0 to 255 that you can assign into. Binary mode (rb, wb) reads and writes those directly, with no decoding, which is the only way to handle a file that is not text. readinto fills a buffer you already own and is the one function here that is genuinely unusual.
Files and Streams Guide 25 of 25 Advanced
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 15 min
bytes and bytearray are Python 3 types. In Python 2, str was bytes and bytearray existed but was rarely used. Everything on this page is Python 3 only.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the binary end of the file objective. This matters because text mode changes the bytes on the way through - so a binary file opened that way comes back altered, and often will not be read at all.
- using a
bytearray, which is a mutablebytes - meeting the two ways it refuses
- building one five different ways
- writing a binary file, and filling a buffer you already own with
readinto - seeing why text mode is not an option for binary data
Before you start
-
A bytearray is a mutable bytes
-
The two ways it refuses
-
Building one
-
Writing a binary file
-
readinto, into a buffer you already own
-
Why text mode is not an option for binary data
-
What the exam does with this objective