File Handling in Python
Presented by Ruthvik Reddy
Introduction
File Handling is the process of creating, reading, writing, and updating files using
Python. It allows programs to store data permanently 4 accessible even after
the program ends.
Why File Handling Matters
Real-World Applications
Permanent Storage Reliability
Student Management System
Stores data permanently Makes applications more
Banking System
and prevents data loss reliable by allowing
Attendance System
after program execution. retrieval of saved
information. Hospital Records
Billing Software
File Modes & Core Functions
Common Functions
Mode Purpose
open()
r Read existing data
Opens a file for reading or writing.
w Write data (creates/overwrites file)
read()
a Append new data
Reads the content of a file.
x Create a new file
write()
Writes data into a file.
close()
Closes the file to free resources.
Two Methods of File Handling
Traditional Method Recommended Method (with)
file = open("[Link]", "w") with open("[Link]", "w") as file:
[Link]("Ruthvik") [Link]("Ruthvik")
[Link]()
Automatically closes the file. Cleaner code, prevents resource
Open the file, perform read/write, then close the file manually. leaks, and is the recommended Python practice.
Code Demonstration
Writing Data Output
with open("[Link]", "w") as file: Ruthvik
[Link]("Ruthvik")
Using the with statement, we write data to a file and read it back
Reading Data — no manual closing required.
with open("[Link]", "r") as file:
print([Link]())
Quick Assessment
MCQ Highlights Practical Thinking
1. MCQ 1: Which function is used to open a file in Python? Question: Write a Python program to:
A. open()
Create a file named [Link]
B. write()
C. read() Store your Name and Roll Number in the file
D. close() Read the file and display its contents on the screen
2. MCQ 2: Which file mode is used to add data without deleting
existing content?
A. r
B. a
C. w
D. x
3. MCQ 3: What is the main advantage of using the with statement?
A. It deletes the file automatically.
B. It makes the file read-only.
C. It automatically closes the file after use.
D. It opens multiple files at once.
Thank You
Any Questions?