Working with Streams in Python

1 hour
  • 2 Learning Objectives

About this Hands-on Lab

We are all used to working with files on disk. Reading and writing files to disk is second nature to anyone that does more with a computer than just emailing and web surfing.

Streams are representation of files in memory. Using standard file i/o, when opening and reading a file on disk, the contents are placed in memory. This “memory file” can be used to write a new file or write changes to the old one. Using the `io` library, a “memory file” can be used to send the contents to other applications without ever writing them to disk.

In this lab you will get a chance to use streams to copy a file, and to provide an in-memory file for consumption by a different application.

**Please Note:** The contents of `book.txt` was taken from Shakespeare’s Sonnets.

Learning Objectives

Successfully complete this lab by achieving the following learning objectives:

Create a Copy for the Editing Department

Please follow guiding comments in the streams.py file. You will be asked to create a function from scratch that takes an input and an output, and then makes a copy of the input to the output.


import io

def copy_book(input, output):
    """
    write the input to the output
    """
    output.write(input.read())

if __name__ == "__main__":

    # author's novel is stored in file `book.txt`
    # create a copy of the book for the editing department
    # append _text to the end of the name of the copy
    # student input needed, please use book_input and book_copy
    # as the handles to the files
    book_input = open("book.txt", "r+b")
    book_copy = open("book_edit.txt", "w+b")

    copy_book(book_input, book_copy)

    book_input.seek(0)
    book_copy.seek(0)

    # test file exists
    try:
        f = open("book_edit.txt", "r+b")
    except FileNotFoundError:
        print("book_edit.txt does not exist")
    finally:
        f.close()

    # test file contents are the same
    assert book_input.read() == book_copy.read()

    # code below this is not shown
Generate a BytesIO Object of Book

Please follow guiding comments in the streams.py file. You will be asked to create a BytesIO object with the book contents. Finally, you will be asked to close all open i/o streams.


    # code above this is not shown

    # write book to a BytesIO object using function copy_book
    # make sure the cursor is at the start of each file (memory file also)
    # send to copy function
    book_stream = io.BytesIO()

    book_input.seek(0)
    copy_book(book_input, book_stream)

    book_stream.seek(0)
    book_input.seek(0)

    # test file exists
    if not book_stream.readable():
        print("book_stream does not exist")
        exit(1)

    # test
    assert book_input.read() == book_stream.getvalue(), f"Expected: {book_copy.read()}nGot: {book_stream.getvalue()}"

    # close all open files
    book_input.close()
    book_copy.close()
    book_stream.close()

    # test
    assert book_input.closed == True
    assert book_copy.closed == True
    assert book_stream.closed == True

Additional Resources

At Atlantic Publishing, a process has been implemented for what should happen once an author has submitted a manuscript. First, a copy of the book is created and marked for editing by appending edit to the name of the file. Second, a BytesIO of the book is prepared for consumption by the Printing department. This allows the printers to set up the parameters while the Editing department is working with the actual text.

Logging In

There are a couple of ways to get in and work with the code. One is to use the credentials provided in the hands-on lab page, log in with SSH, and use a text editor in the terminal.

The other is using VS Code in the browser. If you'd like to go this route, then you will need to navigate to the public IP address of the workstation server (provided in the hands-on lab overview page) on port 8080 (example: http://PUBLIC_IP:8080). Your password will be the same password that you'd use to connect over SSH.

What are Hands-on Labs

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Get Started
Who’s going to be learning?

How many seats do you need?

  • $499 USD per seat per year
  • Billed Annually
  • Renews in 12 months

Ready to accelerate learning?

For over 25 licenses, a member of our sales team will walk you through a custom tailored solution for your business.


$2,495.00

Checkout
Sign In
Welcome Back!

Psst…this one if you’ve been moved to ACG!