liveBook · Manning

Readlines

As explained in A Pythonic Adventure: From Python basics to a working web app

The Python file readlines method returns the lines read from a file as a list of strings.

Use readlines() when a file’s contents need to become a list instead of one large string. Each list item represents one line and usually includes its newline character. section 5.0

Read a drink menu

For a file containing coffee, chocolate, and decaf, f.readlines() produces ['coffee\n', 'chocolate\n', 'decaf\n']. Check type(drinks) to see that the result is a list. To remove the newline characters, loop over the items and apply strip(). section 5.0

f = open("drinks.txt")
drinks = f.readlines()
print(drinks)

Compare the readlines() call with its printed list result and type check. section 5.0

A practical file-reading pattern is:

  • Call readlines() on an opened file. section 5.0
  • Loop through the returned lines, strip each item, and append the cleaned value to a new list. section 5.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Shows the return type, newline characters, and a loop-based cleanup pattern, but not lower-level file internals.
Examples
Uses drinks.txt, flavors.txt, and toppings.txt to build cleaned menu lists.
What it assumes
Assumes basic variables and file opening, while teaching the difference between strings and lists from a concrete example.
What you can do after
Apply it via Python file objects to read line-based data and prepare it for menu selection.
How it connects
Connects file objects with lists, strings, loops, and strip().

Also explained in

Compare how 2 books explain readlines →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.