File Handling in Python
Learn how Python can create, read, write, update and manage files stored on a computer.
What is File Handling?
File handling means working with files using a program.
In Python, we can use file handling to read existing data from a file, create new files, write data into files and update existing file content.
Why Do We Need File Handling?
Variables store data temporarily while a program is running. Files allow us to store data so that it can be used again later.
Store Data
Save information permanently in files.
Read Data
Read previously stored information.
Process Data
Use file data inside Python programs.
File Handling Diagram
A basic file-handling process can be understood through these steps:
Python Program
Application needs to work with stored data.
Open
Open the file using
open().
Read
Get data from the file.
Write
Add or update file data.
Close
Finish using the file.
Stored File
Data remains available for future use.
Opening a File
Python provides the built-in open()
function to work with files.
file = open("example.txt", "r")
Here:
-
example.txtis the file name. -
"r"means read mode. -
filestores the file object.
File Opening Modes
The mode tells Python what we want to do with the file.
| Mode | Meaning |
|---|---|
r |
Read the file. |
w |
Write to the file. Existing content can be replaced. |
a |
Add data to the end of the file. |
x |
Create a new file and fail if it already exists. |
rb |
Read a binary file. |
wb |
Write binary data. |
Reading a File
The read() method is used to read the
file content.
file = open("example.txt", "r")
data = file.read()
print(data)
file.close()
This reads the complete content of the file.
Writing to a File
The w mode is used to write data.
file = open("example.txt", "w")
file.write("Hello Python")
file.close()
The text is written into the file.
Appending Data
The a mode adds new data at the end
of the file.
file = open("example.txt", "a")
file.write("\nWelcome to Python")
file.close()
Existing content is kept and the new content is added at the end.
Using the with Statement
Python provides the with statement to
work with files more safely and conveniently.
with open("example.txt", "r") as file:
data = file.read()
print(data)
After the with block finishes, Python
handles the file resource automatically.
Common File Methods
| Method | Purpose |
|---|---|
read() |
Reads the file content. |
readline() |
Reads one line. |
readlines() |
Reads lines into a list. |
write() |
Writes text to a file. |
writelines() |
Writes multiple strings. |
close() |
Closes the file. |
Text Files and Binary Files
Files are commonly handled in two broad forms: text and binary.
Text Files
Store text-based content such as:
- TXT files
- CSV files
- JSON files
Binary Files
Store data such as:
- Images
- PDF files
- Other binary content
Basic File Handling Flow
Step 1: Decide which file you need to work with.
↓
Step 2: Open the file using the required mode.
↓
Step 3: Read or write data.
↓
Step 4: Save or finish the operation.
↓
Step 5: Close or automatically release the file resource.
Example 👀🔓
Suppose a training institute wants to store student information.
Name,Course,Fees
Rahul,Python,45000
Priya,Java,40000
Python can read this information from a file, process it and save updated information.
Later in this module we will learn how to work with CSV and JSON files in more detail.
Common Mistakes
- Using the wrong file path.
- Using the wrong file mode.
-
Forgetting to close a file when not using
the
withstatement. - Accidentally replacing existing content with write mode.
- Trying to read a file that does not exist.
Practice Programs
- Create a text file using Python.
- Write three lines into the file.
- Read the complete file content.
- Read the file one line at a time.
- Append new data to the file.
-
Read a file using the
withstatement.
File Handling Topics
Reading Files
Read text and data from files.
Writing Files
Create and write file content.
Files & Directories
Work with paths, files and folders.
CSV Files
Read and write CSV data.
JSON Files
Read and write JSON data.
Practice
Apply file-handling concepts in programs.
Summary
File handling allows Python programs to work with
stored data. The open() function is used
to open files in different modes such as
r, w and a.
Python provides methods such as read(),
write() and close().
The with statement provides a convenient
way to work with files and handle the file resource
automatically. In the upcoming topics, we will study
reading files, writing files, directories, CSV files
and JSON files in detail.