What is File Handling?
“File handling allows you to interact with files stored on your computer. You can create, read, write, and update files directly from your Python code.”
Example Use Cases:
- Automating report generation.
- Reading large datasets for analysis.
- Logging activities in an application.
Modes of File Handling in Python
“When working with files, you can open them in different modes:
r
: Read modew
: Write modea
: Append moder+
: Read and write modex
: Create a file but throw an error if it already exists.”
Reading a File in Python
“Let’s start with reading files. Suppose you have a file named example.txt
containing some data.”
with open("example.txt", "r") as file:
content = file.read()
print(content)
“This reads the entire content of the file and prints it. The with
statement ensures the file closes automatically.”
Writing to a File
“Now, let’s write data into a file. If the file doesn’t exist, Python creates it.”
with open("output.txt", "w") as file:
file.write("Hello, this is written by Python!")
“This will overwrite the file if it already exists. Be cautious while using w
mode.”
Appending Data to a File
“What if you don’t want to overwrite the file but instead add new data? Use append mode (a
).”
with open("output.txt", "a") as file:
file.write("\nAdding a new line to the file.")
Reading Files Line by Line
- “For large files, reading line by line saves memory.”
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Examples :
- A school generates a report for each student
students = ["Saravana", "Anjali", "Rahul"]
with open("students_report.txt", "w") as report:
for student in students:
report.write(f"Report for {student}\n")
report.write("Maths: 85, Science: 90, English: 88\n\n")
2. Create backups of important data by copying files.
def backup_file(source, destination):
with open(source, "r") as src:
data = src.read()
with open(destination, "w") as dest:
dest.write(data)
backup_file("important_data.txt", "backup_important_data.txt")
print("Backup created successfully!")
Use Case: Periodic backups for financial reports or user records.
Inventory Management in Retail
def update_inventory(item, quantity):
with open("inventory.txt", "a") as inventory_file:
inventory_file.write(f"{item}: {quantity}\n")
update_inventory("Laptop", 10)
update_inventory("Smartphone", 15)
print("Inventory updated!")
Use Case: Managing stock for e-commerce websites or retail stores.
Maintaining an Attendance Log
def mark_attendance(student_name, date):
with open("attendance_log.txt", "a") as log:
log.write(f"{student_name} attended on {date}\n")
mark_attendance("Saravana", "2024-11-20")
mark_attendance("Anjali", "2024-11-20")
print("Attendance marked!")