Need to process a saved task list? A file stores the data; a Python file object is the stream returned by open() that lets you read or write it. The object reports properties such as its name, mode, and encoding. The mode matters: the default 'r' permits reading, not writing. section 11.1.1
Use `with open("tasks.txt") as file:` for ordinary reads. Work with `file` inside the block; it closes when the block ends. This is preferable to relying on a separate `close()` call, which is easy to forget. section 11.1.1
Listing 11.2 Using with to open a file
with open("tasks.txt") as file: #1
print(f"file object: {file}")
data = file.read()
print(data)
# output the following lines:
file object: <_io.TextIOWrapper name='tasks.txt' mode='r' encoding='UTF-8'>
1001,Homework,5
1002,Laundry,3
1003,Grocery,4
Open a task file, print the file object, and read its contents within a with block. section 11.1.1
Choose a reading method to fit the job:
- `read()` returns all text as one string; avoid loading an entire large file when memory is a concern. section 11.1.1 section 11.1.2
- `for line in file` processes one line at a time. Strip its line break before splitting fields; `readline()` takes one line when that is all you need. section 11.1.2
- `readlines()` makes a list of lines when the file is small enough and you want to modify the resulting list. section 11.1.2
Listing 11.3 Reading the file as a generator
from collections import namedtuple
Task = namedtuple("Task", "task_id title urgency") #1
with open("tasks.txt") as file:
for line in file:
stripped_line = line.strip() #2
task_id, title, urgency = stripped_line.split(",") #3
task = Task(task_id, title, urgency)
print(f"{stripped_line}: {task}")
# output the following lines:
1001,Homework,5: Task(task_id='1001', title='Homework', urgency='5')
1002,Laundry,3: Task(task_id='1002', title='Laundry', urgency='3')
1003,Grocery,4: Task(task_id='1003', title='Grocery', urgency='4')
Each task row is stripped, split on commas, and converted to a task record as the file is iterated. section 11.1.2
To save text, open with 'w' and call `write()` for a string or `writelines()` for a sequence. Write mode can create and truncate a file; use 'a' to append instead. `writelines()` does not insert line breaks, so include them in the strings yourself. Writing through a file opened in default read mode raises an error. section 11.1.3
Listing 11.6 Writing to a new file
with open("tasks_new.txt", "w") as file: #1
print("File:", file)
result = file.write(data)
print("Writing result:", result)
# output the following lines:
File: <_io.TextIOWrapper name='tasks_new.txt' mode='w' encoding='UTF-8'>
Writing result: 45
Writing task data to a new text file returns the number of characters written. section 11.1.3
A file object can also connect to a binary file: `pickle.dump()` receives one opened with 'wb' to preserve Python objects. Moving, copying, or selecting files by modification time is a different task—it acts on files as whole items rather than reading their contents. section 11.3.1 section 11.4







