Python - Read file one byte at a time

By xngo on July 31, 2019

The examples below show how to read file one byte at a time using Python. Obviously, it is not efficient. You should use a bigger buffer size instead of 1. On the operating system level, file is read in block size. For example, if the block size is 2048 bytes and you call read(1) twice, then the operating system might fetch 2 times the block size.

Read file forward one byte at a time

The code example below will read file one byte at the time from the beginning to the end.

with open("myfile.txt", "rb") as file:
    byte = file.read(1)         # Read 1st byte.
    print(byte.decode())        # Print the 1st byte as character.
    while byte:
        byte = file.read(1)     # Read subsequent byte.
        print(byte.decode())    # Print byte as character.

Read file backward one byte at a time

The code example below will read file one byte at the time from the end to the beginning. It uses file.seek() to set the current position relative to the file's end(os.SEEK_END). It loops until file.seek() throw an exception, which means there is no more data to read.

import os
with open("myfile.txt", "rb") as file:
    pos = 1
    has_data = True
    while has_data:
        try:
            file.seek(-1*pos, os.SEEK_END)
            byte = file.read(1)
            print(byte.decode())
            pos += 1
        except:
            has_data = False

Or, you can use file.seek(-1, os.SEEK_END) to jump to the end of file and read the previous byte from the current position. Here is the code example.

import os
with open("myfile.txt", "rb") as file:
    # Jump to the end of file.
    file.seek(-1, os.SEEK_END)
 
    has_data = True
    while has_data:
        try:
            byte = file.read(1)
            print(byte.decode())
            file.seek(-2, os.SEEK_CUR) # Move 2 steps backward to read the previous byte.
        except:
            has_data = False

Note that after you read 1 byte, the position is moved 1 step forward. That is why you have to move 2 steps backward in order to read the previous byte.

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.