File Handling in Python (Read, Write, and Append)
Introduction
In real-world programs, we often need to store data permanently.
Python provides simple ways to work with files using built-in functions.
With file handling, you can:
Create and open files
Read from files
Write or append data
Close files safely
1. Opening a File
You can open a file using the built-in open() function.
Syntax:
file = open("filename", "mode")
| Mode | Description |
|---|---|
"r" |
Read (default) |
"w" |
Write (overwrites existing content) |
"a" |
Append (adds data to the end) |
"r+" |
Read and Write |
2. Writing to a File
Example:
file = open("example.txt", "w")
file.write("Welcome to Python File Handling!")
file.close()
Output:
A new file named example.txt is created with the text inside.
3. Reading from a File
Example:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
Output:
Welcome to Python File Handling!
4. Appending Data to a File
Example:
file = open("example.txt", "a")
file.write("\nThis line is added later.")
file.close()
Output:
The new line will be added without removing old data.
5. Using with Statement (Best Practice)
Using with automatically closes the file — even if an error occurs.
Example:
with open("example.txt", "r") as f:
data = f.read()
print(data)
Output:
Welcome to Python File Handling!
This line is added later.
6. Reading Files Line by Line
with open("example.txt", "r") as f:
for line in f:
print(line.strip())
Output:
Welcome to Python File Handling!
This line is added later.
7. Writing Lists to a File
fruits = ["Apple\n", "Banana\n", "Cherry\n"]
with open("fruits.txt", "w") as f:
f.writelines(fruits)
Output:
File fruits.txt will contain:
Apple
Banana
Cherry
8. Checking File Existence
You can check whether a file exists before using it.
import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")
Output:
File exists!
Key Points to Remember
Always close the file (or use with)"w" overwrites the file"a" appends to the existing file"r" reads existing content
Challenge for You
Write a Python program that:
-
Creates a file named data.txt
-
Writes 5 lines into it
-
Reads and displays the content line by line
Final Thoughts
File handling is essential for data storage and retrieval in applications.
You’ll use it frequently when working with databases, logs, and reports.
In the next lesson, we’ll explore Exception Handling in Python, which ensures your program runs smoothly even when errors occur.
.png)
.png)
Comments
Post a Comment