Data stored inside a program exists only while the program is running. Once the program stops, all variables and their values are lost from memory. In real-world applications, however, information such as student records, employee details, invoices, reports, customer data, and application logs must be stored permanently. Python provides file handling to save data in files so it can be accessed, modified, and reused even after the program has finished executing.
File handling is one of the most important topics in Python because almost every application reads data from files or writes data to files. Whether you are building a desktop application, a website, a machine learning project, or a data analytics solution, file handling allows your programs to work with persistent data.
In this lesson, you will learn what file handling is, why it is important, understand different types of files, create your first file, and explore practical examples from real-world programming.
After completing this lesson, you will be able to:
File handling is the process of creating, opening, reading, writing, updating, and closing files using a programming language. In Python, files are managed using built-in functions that make it easy to store and retrieve data.
A file is a named location on a storage device where information is permanently stored. Unlike variables, files retain their contents even after the program ends.
Without file handling, every time a program runs, users would have to enter the same information again. File handling enables applications to save information for future use.
Some common uses include:
Python mainly works with two types of files.
Text files store information in a human-readable format.
Common examples include:
.txt.csv.json.xml.htmlExample of a text file:
Name: Rahul
Course: Python
Marks: 92
Binary files store data in binary (0s and 1s). They are not directly readable by humans.
Common examples include:
.jpg.png.pdf.mp3.exeBinary files are commonly used for images, videos, audio files, and executable programs.
File handling is used in almost every software application.
| Application | Purpose |
|---|---|
| School Management System | Store student records |
| Hospital Management | Save patient information |
| Banking Software | Maintain transaction history |
| Data Analytics | Read CSV and Excel datasets |
| Web Applications | Store configuration files |
| Machine Learning | Load training datasets |
Python creates files using the built-in open() function. If the specified file does not exist and an appropriate mode is used, Python creates it automatically.
file = open("student.txt", "w")
file.write("Welcome to Python File Handling")
file.close()
print("File Created Successfully")
Output
File Created Successfully
The program creates a text file named student.txt, writes one line of text into it, and closes the file.
open() creates or opens the file."w" mode opens the file for writing.write() stores text inside the file.close() saves changes and releases system resources.file = open("message.txt", "w")
file.write("Python makes file handling simple.")
file.close()
print("Message Saved")
Output
Message Saved
After running the program, the file message.txt contains:
Python makes file handling simple.
Consider the following program.
file = open("sample.txt", "w")
file.write("Hello Python")
file.close()
print("Completed")
Execution Steps
Hello Python is written into the file.Output
Completed
In this section, you learned what Python file handling is, why it is important, the difference between text and binary files, the advantages of storing data in files, and how to create your first file using Python. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to open files using the open() function, understand different file modes such as r, w, a, and x, properly close files, and work with files safely in Python.
In the previous section, you learned what file handling is, why it is important, the difference between text and binary files, and how to create your first file. Before you can read or write data, Python must first open the file. The way a file is opened depends on the operation you want to perform, such as reading, writing, appending, or creating a new file.
In this section, you will learn how to open files using the open() function, understand different file modes, properly close files, and work with files safely in Python.
open() FunctionPython uses the built-in open() function to open a file.
file = open(filename, mode)
Parameters
file = open("student.txt", "r")
print(file)
file.close()
Output
<_io.TextIOWrapper name='student.txt' mode='r' encoding='UTF-8'>
The file is opened in read mode and assigned to the variable file.
The file mode determines what operations can be performed on a file.
| Mode | Description |
|---|---|
r |
Read an existing file. |
w |
Write to a file. Creates a new file if it does not exist and overwrites existing content. |
a |
Append new data at the end of an existing file. |
x |
Create a new file. Raises an error if the file already exists. |
r+ |
Read and write an existing file. |
w+ |
Read and write after clearing existing contents. |
a+ |
Read and append data. |
rb |
Read a binary file. |
wb |
Write a binary file. |
r)The r mode opens an existing file for reading. If the file does not exist, Python raises a FileNotFoundError.
file = open("student.txt", "r")
file.close()
w)The w mode opens a file for writing. If the file already exists, all existing data is removed before writing new content.
file = open("student.txt", "w")
file.write("Python File Handling")
file.close()
a)The a mode adds new content at the end of an existing file without removing previous data.
file = open("student.txt", "a")
file.write("\nWelcome")
file.close()
x)The x mode creates a completely new file. If the file already exists, Python raises a FileExistsError.
file = open("report.txt", "x")
file.close()
r+)This mode allows both reading and writing without deleting existing data.
file = open("student.txt", "r+")
file.write("Hello")
file.close()
w+)The w+ mode clears the file contents before allowing reading and writing.
file = open("student.txt", "w+")
file.write("Python")
file.close()
a+)The a+ mode allows both appending and reading while preserving existing data.
file = open("student.txt", "a+")
file.write("\nData Analytics")
file.close()
After completing file operations, always close the file using the close() method.
file = open("student.txt", "r")
file.close()
Closing a file releases system resources and ensures that all data is properly saved.
Python provides useful attributes to inspect an opened file.
file = open("student.txt", "r")
print(file.name)
print(file.mode)
print(file.closed)
file.close()
print(file.closed)
Output
student.txt
r
False
True
file = open("notes.txt", "w")
file.write("Python File Handling Lesson")
print(file.mode)
file.close()
print(file.closed)
Output
w
True
Consider the following program.
file = open("sample.txt", "w")
file.write("Hello Python")
file.close()
print("Completed")
Execution Steps
Output
Completed
w mode when the existing data should be preserved.r mode for a file that does not exist.x mode for an existing file.In this section, you learned how to open files using the open() function, explored all commonly used file modes including r, w, a, x, r+, w+, and a+, and understood why closing files is important. You also learned how to inspect file properties and avoid common mistakes. In the next section, you will learn how to read data from files using methods such as read(), work with file pointers, understand text versus binary reading, and apply file reading techniques in practical Python programs.
In the previous section, you learned how to open files using different file modes such as r, w, a, and x. Once a file has been opened, the next step is reading its contents. Python provides several methods for reading files, allowing you to read an entire file, a single line, multiple lines, or a specific number of characters.
In this section, you will learn how to read files using Python, understand different reading methods, work with the file pointer, compare text and binary reading, and explore practical examples.
Python provides several built-in methods for reading data from files.
The most commonly used methods are:
read()readline()readlines()read() MethodThe read() method reads the entire contents of a file and returns it as a string.
file.read()
Suppose student.txt contains:
Rahul
Python
92
Python program:
file = open("student.txt", "r")
content = file.read()
print(content)
file.close()
Output
Rahul
Python
92
The entire file is read at once.
You can specify the number of characters to read.
file = open("student.txt", "r")
print(file.read(5))
file.close()
Output
Rahul
Only the first five characters are read.
readline() MethodThe readline() method reads one line at a time.
file = open("student.txt", "r")
print(file.readline())
print(file.readline())
file.close()
Output
Rahul
Python
Each call to readline() moves the file pointer to the next line.
readlines() MethodThe readlines() method reads all lines and returns them as a list.
file = open("student.txt", "r")
lines = file.readlines()
print(lines)
file.close()
Output
['Rahul\n', 'Python\n', '92']
Each element of the list represents one line from the file.
for LoopReading files line by line using a loop is memory-efficient, especially for large files.
file = open("student.txt", "r")
for line in file:
print(line.strip())
file.close()
Output
Rahul
Python
92
The strip() method removes the newline character from each line.
Whenever Python reads data from a file, it keeps track of the current reading position using a file pointer.
After reading some data, the pointer moves forward automatically.
file = open("student.txt", "r")
print(file.read(5))
print(file.read(5))
file.close()
Output
Rahul
Python
The second read() continues from where the first one stopped.
tell() MethodThe tell() method returns the current position of the file pointer.
file = open("student.txt", "r")
print(file.tell())
file.read(5)
print(file.tell())
file.close()
Output
0
5
The pointer starts at position 0 and moves after reading characters.
seek() MethodThe seek() method moves the file pointer to a specified position.
file = open("student.txt", "r")
file.read(5)
file.seek(0)
print(file.read())
file.close()
Output
Rahul
Python
92
The pointer returns to the beginning of the file.
Binary files must be opened using binary mode.
file = open("photo.jpg", "rb")
data = file.read(20)
print(data)
file.close()
Output
b'\xff\xd8\xff\xe0...'
Binary data is displayed as bytes instead of readable text.
for loop for large files.read() only for smaller files.seek() when you need to reread data.read(size) when processing large datasets in chunks.file = open("notes.txt", "r")
for line in file:
print(line.strip())
file.close()
Output
Python Basics
Variables
Loops
Functions
Consider the following program.
file = open("student.txt", "r")
content = file.read()
print(content)
file.close()
Execution Steps
read() retrieves the complete contents.content.Output
Rahul
Python
92
read() on extremely large files.In this section, you learned how to read files using read(), readline(), readlines(), and for loops. You also explored file pointers, the tell() and seek() methods, binary file reading, best practices, and performance tips. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Reading Files in Python.
In this lesson, you learned the fundamentals of Python file handling, one of the most essential topics in Python programming. File handling allows programs to store information permanently so that it can be accessed, updated, and reused even after the program has finished executing.
You began by understanding what file handling is, why it is important, and the difference between text files and binary files. You also explored real-world applications where file handling is used, such as student management systems, banking software, web applications, machine learning, and data analytics.
Next, you learned how to open files using the open() function and explored various file modes including r, w, a, x, r+, w+, and a+. You also learned why closing files with close() is important.
Finally, you explored different methods for reading files, including read(), readline(), readlines(), and reading files using a for loop. You also learned about file pointers, the tell() and seek() methods, binary file reading, best practices, and performance tips.
Understanding file handling is an important foundation because almost every Python application works with files, whether it is reading datasets, storing user information, generating reports, or processing configuration files.
open() function to work with files.read(), readline(), or readlines() to read files.for loop to efficiently process large files.tell() method returns the current file pointer position.seek() method moves the file pointer to a specified location.File handling is the process of creating, opening, reading, writing, updating, and closing files.
It allows data to be stored permanently instead of existing only while a program is running.
The open() function.
Text files store readable characters, while binary files store data as bytes.
The r mode.
The a mode.
Closing a file saves changes and releases system resources.
tell() method do?It returns the current position of the file pointer.
seek() method?It moves the file pointer to a specified position.
Reading the file line by line using a for loop.
x mode.for loop.tell() method to display the file pointer position.seek() method to move the file pointer back to the beginning.readline().open() function?r, w, and a modes.read(), readline(), and readlines()?tell() and seek() work?Create a Python program that demonstrates basic file handling operations.
Your program should:
students.txt.tell().seek(0) to move back to the beginning and display the contents again.========== STUDENT NOTES READER ==========
Creating File...
File Created Successfully
Reading Complete File
Rahul
Priya
Amit
First Line
Rahul
Current File Pointer
18
Pointer Reset Successfully
Reading Again
Rahul
Priya
Amit
==========================================
Congratulations! You have learned the fundamentals of Python File Handling. You now understand how to create files, open files using different modes, read file contents, work with file pointers, and follow best practices for handling files efficiently.
In the next lesson, you will learn Reading Files in Python: Complete Guide for Beginners. You will explore advanced file reading techniques, understand efficient reading strategies for large files, compare different reading methods in detail, and work with practical real-world examples.