Reading Files in Python

Our first program will demonstrate how to read files in Python. Here’s the full source code with explanations:

import os

# This helper function will streamline our error checks
def check(e):
    if e:
        raise e

def main():
    # Perhaps the most basic file reading task is
    # slurping a file's entire contents into memory.
    with open('/tmp/dat', 'r') as file:
        dat = file.read()
    print(dat)

    # You'll often want more control over how and what
    # parts of a file are read. For these tasks, open
    # the file and use various read methods.
    with open('/tmp/dat', 'r') as f:
        # Read some bytes from the beginning of the file.
        # Allow up to 5 to be read but also note how many
        # actually were read.
        b1 = f.read(5)
        print(f"{len(b1)} bytes: {b1}")

        # You can also seek to a known location in the file
        # and read from there.
        f.seek(6)
        b2 = f.read(2)
        print(f"{len(b2)} bytes @ 6: {b2}")

        # The io package in Python doesn't have a direct equivalent
        # to Go's ReadAtLeast, but we can achieve similar functionality
        # by combining seek and read
        f.seek(6)
        b3 = f.read(2)
        print(f"{len(b3)} bytes @ 6: {b3}")

        # There is no built-in rewind, but
        # seek(0) accomplishes this.
        f.seek(0)

        # The io module provides some functions that may
        # be helpful for file reading. For example, we can use
        # readline() to read a single line.
        line = f.readline()
        print(f"Line: {line.strip()}")

if __name__ == "__main__":
    main()

To run the program, first create a test file:

$ echo "hello" > /tmp/dat
$ echo "python" >> /tmp/dat
$ python reading_files.py
hello
python
5 bytes: hello
2 bytes @ 6: py
2 bytes @ 6: py
Line: hello

In this Python version:

  1. We use the with statement for file handling, which automatically closes the file when we’re done.

  2. Instead of os.ReadFile, we use open() and read() to read the entire file.

  3. Python’s seek() method is similar to Go’s Seek().

  4. Python doesn’t have a direct equivalent to io.ReadAtLeast, but we can achieve similar functionality by combining seek() and read().

  5. We use readline() to demonstrate reading a single line, which is similar to using a buffered reader in Go.

  6. Error handling in Python is typically done with try/except blocks, but for simplicity, we’ve used a check() function similar to the Go example.

This example demonstrates various ways to read files in Python, including reading entire files, reading specific byte ranges, seeking to positions in the file, and reading lines.