Reading a File Byte by Byte in Python

In Python, you can open and read a file in chunks by specifying the number of bytes you want to read at a time using the read method.

filename.read(n)

Here, the argument n inside the parentheses represents the number of bytes to read.

When you specify the number of bytes, the read method will read N bytes at a time, without pausing at the end of each record.

    A Practical Example

    Let's consider a file named prova.txt that contains three records:

    123
    45678
    9

    The first record has three characters, the second has five, and the third has one.

    First, open the file in read mode:

    f = open('prova.txt', 'r')

    Now, read the file's content in chunks of four bytes each:

    >>> f.read(4)
    '123\n'
    >>> f.read(4)
    '4567'
    >>> f.read(4)
    '8\n9\n'

    The read method reads the file's content in groups of four bytes.

    Note: The file content includes the \n symbol, which is the newline character. In this context, the \n symbol doesn't separate the file's records but is treated as a regular ASCII character.

     

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Managing Files in Python