Reading and Writing in A Text File
Reading and Writing in A Text File
Lesson Overview
Lesson Duration
80 minutes
Lesson Objectives
Materials Needed
Lesson Structure
Introduction (10 minutes)
Opening Files
Explain the open() function and
its syntax: file = open(filename,
mode) .
Discuss different modes: 'r' ,
'w' , 'a' , 'x' , 'b' , 't' .
Demonstrate opening a file in
read mode:
Appending to a File
Open a file in append mode:
Copying Content
Demonstrate copying content
from one file to another:
Best Practices
Always close files or use the
with statement.
Handle exceptions to manage
errors gracefully.
Error Handling
Use try-except blocks to handle
file operations:
try:
with open('example.txt', 'r') as
file:
contents = file.read()
print(contents)
except FileNotFoundError:
print('File not found')
Conclusion and Q&A (5 minutes)
Summary
Recap the key points covered in
the lesson.
Questions
Open the floor for any questions
from the students.
Task
Create a Python script that reads
content from a file, modifies it,
and writes the modified content
to a new file.
Instructions
Provide a sample text file.
Ask students to read the content,
make a specific change (e.g.,
replace a word), and write the
modified content to a new file.
Homework
Assign a task to create a Python
script that reads data from a CSV
file and writes a summary of the
data to a new text file.
References
https://tutorpython.com/file-input-
output-in-python/
https://hexlet.io/courses/python-
io/lessons/opening-and-closing/
theory_unit
https://www.geeksforgeeks.org/
read-content-from-one-file-and-
write-it-into-another-file/
https://slideplayer.com/slide/
14669441/
https://
programminghistorian.org/en/
lessons/working-with-text-files
https://
nsworldinfo.medium.com/
harnessing-the-power-of-input-
output-and-file-handling-in-
python-8a1fa72900b3
https://wiingy.com/learn/python/
file-
handling-in-python/