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


