๐ฏ Learning Objectives
By the end of this lesson, learners will be able to:
-
Open and close text files using
open()
andwith
statement -
Read the content of files using
.read()
,.readline()
, and.readlines()
-
Write and append data to files using
.write()
and"w"
/"a"
modes -
Safely manage files using the
with
context manager
๐ Lesson Content
๐น What is File Handling?
File handling allows a Python program to store, retrieve, and manipulate data in external text files.
Python provides built-in methods for:
-
Reading data (
"r"
mode) -
Writing data (
"w"
mode) -
Appending data (
"a"
mode)
๐ธ Opening a File with open()
Syntax:
Mode | Description |
---|---|
"r" |
Read (default); error if file doesnโt exist |
"w" |
Write; creates a new file or overwrites |
"a" |
Append; adds to the file |
"x" |
Create; error if file already exists |
"r+" |
Read and write |
๐ธ Reading from a File
โ Read the whole file:
โ Read one line at a time:
โ Read all lines as a list:
๐ธ Using with
Statement (Best Practice)
โ
with
automatically closes the file when done โ safer and cleaner!
๐ธ Writing to a File
โ ๏ธ
"w"
mode overwrites existing file content.
๐ธ Appending to a File
"a"
mode adds to the end of the file without erasing existing data.
๐ Summary of Reading Methods
Method | Description |
---|---|
.read() |
Reads entire file as a string |
.readline() |
Reads the next single line |
.readlines() |
Reads all lines as a list |
๐ง Mini Practice
Create a file called notes.txt
and:
-
Write three lines into it using
"w"
mode -
Open it again in
"a"
mode and add one more line -
Read and print the entire content using
with open(...)
๐ Assignment
-
Create a file named
diary.txt
-
Write a short entry (3 lines) using
"w"
mode -
Append a second entry using
"a"
mode -
Read the file and print its contents line by line