liveBook · Manning

Read operation

As explained in Python How-To

read is a file-object method that retrieves a specified number of characters or the remaining contents of a file as text or bytes.

Need the contents of a text file as one value? Open the file, call read(), and receive the remaining text as a string. The result can then be split or otherwise processed. Use a with statement so the file closes automatically after reading. section 11.1.1

Listing 11.1 Reading data as a string
text_data = text_file.read()
 
print(type(text_data))      #1
# output: <class 'str'>
 
print(text_data)
# output the following lines:
1001,Homework,5
1002,Laundry,3
1003,Grocery,4

A complete example reads tasks.txt into text_data, confirms the result is a str, and prints the three task rows. section 11.1.1

Choose the reading pattern according to the amount of data and the form needed afterward:

  • Call read() when the entire file is suitably sized and downstream processing benefits from one string. section 11.1.1 section 11.1.2
  • Iterate over the file object when processing lines individually; strip each line break before splitting fields. section 11.1.2
  • Use readlines() when a manageable file should become a mutable list, or use readline() to retrieve one line or a specified character count. section 11.1.2

Read and process task data

with open("tasks.txt") as file: data = file.read() rows = data.splitlines() print(rows) # ['1001,Homework,5', '1002,Laundry,3', '1003,Grocery,4'] This compact pattern keeps the file operation inside the context manager and leaves the retrieved text available for later processing. section 11.1.1

How Python How-To covers it

How deep it goes
Defines whole-file reading, then contrasts line iteration, readlines(), and readline() for scale and processing needs.
Examples
Uses tasks.txt containing comma-separated task rows and converts retrieved lines into processed task data.
What you can do after
Apply it via Python's open() and with statement to retrieve file text, then choose string, line, or list processing.
How it connects
Connects read to file objects, context managers, strings, line iteration, generators, and list processing.

Also explained in

Compare how 3 books explain read operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.