๐ฏ Lesson Objective
To learn how to create, read, write, and manage files in Python using built-in file handling methods.
๐งฉ 1. What Is File Handling?
File handling allows Python programs to store and retrieve data from files.
Common file types: Text files (.txt), CSV files (.csv), JSON files (.json), etc.
โ๏ธ 2. Opening a File
Use the open() function to open a file.
file = open("example.txt", "w") # w โ write mode
File Modes
| Mode | Description |
|---|---|
r | Read (default) |
w | Write (creates new or overwrites) |
a | Append |
x | Create (fails if file exists) |
r+ | Read and write |
โ๏ธ 3. Writing to a File
file = open("example.txt", "w")
file.write("Hello, Python File Handling!\n")
file.write("This is a second line.")
file.close()
๐ 4. Reading from a File
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
โ Output:
Hello, Python File Handling!
This is a second line.
๐ 5. Reading Line by Line
file = open("example.txt", "r")
for line in file:
print(line.strip())
file.close()
Output:
Hello, Python File Handling!
This is a second line.
โ 6. Appending to a File
file = open("example.txt", "a")
file.write("\nAdding a new line.")
file.close()
๐ก๏ธ 7. Using with Statement
Automatically closes the file after operations.
with open("example.txt", "r") as file:
content = file.read()
print(content)
๐งฎ 8. Other Useful File Methods
| Method | Description | Example |
|---|---|---|
read(size) | Reads size characters | file.read(10) |
readline() | Reads one line | file.readline() |
readlines() | Reads all lines into a list | file.readlines() |
tell() | Returns current cursor position | file.tell() |
seek(offset) | Moves cursor to position | file.seek(0) |
truncate() | Truncates file | file.truncate(10) |
๐ 9. Real-Life Example โ Logging Messages
with open("log.txt", "a") as log_file:
log_file.write("User logged in at 10:00 AM\n")
with open("log.txt", "r") as log_file:
logs = log_file.read()
print(logs)
Output:
User logged in at 10:00 AM

Leave a Reply