We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Read File

Now let's start ackshually building BookBot by reading the contents of Frankenstein.

Open and Read a File

Use a with block with the built-in open() function:

with open(path_to_file) as f:
    file_contents = f.read()

The f.read() method returns the file's contents as a string.

The with block will automatically close the file when the block exits, cleaning up resources.

Assignment

  1. python3 main.py
    

Run and submit the CLI tests from the root of your project.

Tips

  • File paths are strings, so remember to put the path in quotes.
  • A relative path starts from your current working directory. Because you're running the program from the project root, the path to the book starts with books/.
  • You don't need to write all your functions and variable names the same as mine; I'm just trying to give you some examples of how you can potentially structure your code. There are many correct ways to write the same program.