UNIT-4
FILE HANDLING
Introduction to File Handling in Python
File handling in Python refers to the process of working with files—such as creating, reading, writing, and
updating them—using Python programs. In real life, data is often stored permanently in files (like text files,
CSV files, or logs), rather than only in temporary variables. File handling allows a program to interact with
these stored files so that data can be saved and retrieved even after the program stops running. This is
especially useful in applications like saving user information, maintaining records, or reading configuration
settings.
In Python, file handling is done using built-in functions like open(). When a file is opened, it must be done in
a specific mode, such as read mode ('r'), write mode ('w'), append mode ('a'), or read/write mode ('r+'). Each
mode defines what operations can be performed on the file. For example, read mode allows you to view the
content, while write mode allows you to overwrite or create new content. After performing operations, it is
important to close the file using close() to free up system resources, although Python also provides a safer
method using with open(...) which automatically handles closing.
File handling also involves methods such as read(), readline(), and readlines() to retrieve data from a file, and
write() or writelines() to store data into a file. These methods help programmers control how much data is
read or written at a time. For example, read() can read the entire file, while readline() reads one line at a time,
making it useful for processing large files efficiently without loading everything into memory.
Overall, file handling is an essential concept in Python because it connects programs with real-world data
storage. Without file handling, data would be lost every time a program ends. By learning file handling,
students can build more practical and powerful applications, such as systems that store user data, process
large datasets, or generate reports. Understanding this concept also lays the foundation for working with
more advanced data formats and databases in the future.
Need of File Handling in Python: File handling is needed because programs often require data to be stored
permanently rather than temporarily. When a program runs, the data stored in variables is lost once the
program stops. File handling solves this problem by allowing data to be saved in files, which can be accessed
later anytime. For example, applications like login systems, student records, or billing systems all depend on
file storage to keep data safe and reusable.
Types of File Modes in Python:
Python provides different file modes that define how a file will be used. The most common modes include
read mode ('r') to view file content, write mode ('w') to create or overwrite a file, and append mode ('a') to
add data without deleting existing content. There are also modes like 'r+' for both reading and writing.
Understanding these modes helps students choose the correct operation and avoid accidental data loss.
Basic Operations on Files:
File handling mainly includes operations such as opening a file, reading data, writing data, and closing the
file. A file is opened using the open() function, after which different methods like read(), write(), and
readline() are used to perform tasks. Once the work is complete, the file should be closed using close() to
ensure proper resource management. Python also provides the with open() statement, which automatically
closes the file and is considered a better practice.
Advantages of File Handling:
File handling allows data to be stored permanently, making programs more useful and realistic. It helps in
managing large amounts of data efficiently and supports data sharing between different programs. It also
reduces manual work, as data can be automatically saved and retrieved whenever needed. This makes file
handling an important concept for building real-world applications.
Example of File Handling:
A simple example of file handling is a student record system in a school. Imagine a program where a teacher
enters student details like name, roll number, and marks. If file handling is not used, all this data will
disappear as soon as the program is closed. But with file handling, this information can be saved in a file
(like a text file), and later the teacher can open the program again to view, update, or add new student
records.
For example, when a new student is added, the program uses write ('w') or append ('a') mode to store the data
in a file. When the teacher wants to check student details, the program uses read ('r') mode to display the
stored information. This way, the data remains safe and can be reused anytime. This example clearly shows
how file handling is used in real life to manage and maintain important data efficiently.
Operations in File Handling:
File handling in Python involves a few basic operations that allow a program to interact with files effectively.
These operations are important because they help in storing, accessing, and modifying data as needed.
1. Opening a File: The first step in file handling is opening a file using the open() function. While opening a
file, we also specify the mode (such as read, write, or append). This step prepares the file so that the program
can perform further actions on it.
2. Reading a File: Reading means accessing the data stored inside a file. Python provides methods like
read(), readline(), and readlines() to read content. This operation is useful when we want to display or process
stored information.
3. Writing to a File: Writing is used to store data into a file. The write() and writelines() methods are used
for this purpose. If the file does not exist, Python creates it, and if it exists, the content may be overwritten
depending on the mode used.
4. Appending to a File: Appending means adding new data to the existing content without deleting the old
data. This is done using append mode ('a'). It is useful when we want to keep adding information, like logs or
records.
5. Closing a File: After completing all operations, it is important to close the file using the close() method.
This frees system resources and ensures that all changes are saved properly. A better way is using with
open() which automatically closes the file.
Opening Files in Python:
Opening a file is the first and most important step in file handling. In Python, a file is opened using the
open() function. This function takes two main arguments: the file name and the mode in which the file should
be opened. For example, open("[Link]", "r") opens a file named [Link] in read mode. If the file is in the
same folder as the program, we can directly use its name; otherwise, we need to provide the full path.
When a file is opened, Python creates a file object that allows us to perform different operations like reading
or writing. It is important to handle files carefully because if a file is not opened properly, operations cannot
be performed. Also, after completing the work, the file should be closed using close() or handled using with
open() to ensure safety and proper memory management.
File Modes in Python:
File modes define how a file will be used—whether we want to read, write, or modify it. Choosing the
correct mode is very important because it directly affects the file’s content. For example, using write mode
('w') can delete existing data, while append mode ('a') keeps old data safe and adds new content at the end.
Python provides several modes to give flexibility while working with files.
Complete File Modes Chart
Mode Meaning Description
'r' Read Opens file for reading only. Error if file does not exist.
'w' Write Opens file for writing. Creates new file or overwrites existing file.
'a' Append Opens file for adding data at the end. Creates file if not exists.
'r+' Read & Write Opens file for both reading and writing. File must exist.
'w+' Write & Read Opens file for reading and writing but overwrites existing data.
'a+' Append & Read Opens file for reading and appending. Data is added at the end.
'rb' Read Binary Opens file for reading in binary format (used for images, etc.).
'wb' Write Binary Opens file for writing in binary format.
'ab' Append Binary Opens file for appending in binary format.
'rb+' Read & Write Binary Opens binary file for both reading and writing.
Opening a File in Python: Opening a file means preparing it so that a program can perform operations like
reading or writing on it. In Python, this is done using the open() function. When a file is opened, Python
creates a file object, which acts like a connection between the program and the file. Without opening a file,
no operation can be performed on it.
Syntax of Opening a File
file_object = open("file_name", "mode")
Explanation of Syntax
file_object → A variable that stores the file reference (you can use any name).
"file_name" → Name of the file you want to open (e.g., "[Link]").
"mode" → Defines how the file will be used (read, write, append, etc.).
Examples of Opening a File
1. Opening a File in Read Mode
file = open("[Link]", "r")
print([Link]())
[Link]()
This opens the file in read mode and displays its content. The file must already exist.
2. Opening a File in Write Mode
file = open("[Link]", "w")
[Link]("Hello Students")
[Link]()
This creates a new file or overwrites an existing file with new data.
3. Opening a File in Append Mode
file = open("[Link]", "a")
[Link]("\nWelcome to Python")
[Link]()
This adds new content at the end without deleting old data.
4. Using with open() (Best Method)
with open("[Link]", "r") as file:
content = [Link]()
print(content)
This method automatically closes the file, so it is safer and recommended.
Second Syntax for Opening a File (Using with open()): In Python, another and better way to open a file is
by using the with open() statement. This method is considered best practice because it automatically handles
closing the file. This means you don’t need to write close() manually, which reduces errors and makes the
code cleaner.
Syntax
with open("file_name", "mode") as file_object:
# file operations
Explanation of Syntax:
with → A keyword that manages resources properly (like files).
open("file_name", "mode") → Opens the file in the given mode.
as file_object → Stores the file in a variable for use inside the block.
Indented block → All operations (read/write) are done inside this block.
Once the block ends, the file is automatically closed.
Examples
1. Reading a File Using with open()
with open("[Link]", "r") as file:
content = [Link]()
print(content)
This reads the file content and prints it. No need to call close().
2. Writing to a File Using with open()
with open("[Link]", "w") as file:
[Link]("Hello Students")
This writes data into the file. If the file exists, it will be overwritten.
3. Appending Data Using with open()
with open("[Link]", "a") as file:
[Link]("\nNew Line Added")
This adds new content at the end of the file without removing old data.
Closing a File in Python: Closing a file means ending the connection between the program and the file after
completing all operations like reading or writing. When a file is opened in Python, the system allocates some
resources (memory and buffer) to it. If the file is not closed properly, these resources remain occupied, which
can slow down the system or cause data corruption. That is why closing a file is an important step in file
handling.
Syntax of Closing a File
file_object.close()
Explanation of Syntax
file_object → The variable that stores the opened file.
close() → A method used to close the file.
Once close() is called, no further reading or writing can be done on that file.
Example of Closing a File
file = open("[Link]", "w")
[Link]("Hello Students")
[Link]()
In this example:
The file is opened in write mode.
Data is written into the file.
Finally, close() is used to properly close the file.
Why Closing a File is Important:
It frees system resources (memory is released).
It ensures all data is properly saved in the file.
It prevents data loss or corruption.
It avoids file access errors in large programs.
Better Alternative (Automatic Closing)
Instead of manually closing the file, Python provides a better method:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
In this method, the file is automatically closed after the block ends, so you don’t need to write close().
File Modes in Python (Explanation with Examples)
1. File Mode: r (Read Mode) in Python
The r mode (read mode) in Python is used to read data from an existing file. In this mode, we can only view
the content of the file; we cannot change, write, or delete anything inside it. If the file does not exist, Python
will give an error.
This mode is mainly used when we want to access and display stored data from a file.
Syntax
file_object = open("file_name", "r")
OR (Recommended)
with open("file_name", "r") as file_object:
Examples of r Mode (Read Mode)
Example 1: Reading full file content
File Content ([Link])
Hello Students
Welcome to Python
File Handling is Easy
Code:
file = open("[Link]", "r")
print([Link]())
[Link]()
Output
Hello Students
Welcome to Python
File Handling is Easy
Explanation: The read() method reads the entire content of a file at once and returns it as a single string.
Example 2: Using with open()
File Content ([Link])
Python is powerful
File handling is important
Practice daily
Code
with open("[Link]", "r") as file:
print([Link]())
Output
Python is powerful
File handling is important
Practice daily
Explanation: The file is automatically closed, so there is no need to explicitly use the close() method.
Example 3: Reading one line using readline()
File Content ([Link])
Line 1: Apple
Line 2: Banana
Line 3: Mango
Code
file = open("[Link]", "r")
print([Link]())
[Link]()
Output
Line 1: Apple
Explanation: The readline() method reads only the first line of a file (one line at a time).
Example 4: Reading all lines using readlines()
File Content ([Link])
Red
Green
Blue
Yellow
Code
file = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
Output
['Red\n', 'Green\n', 'Blue\n', 'Yellow']
Explanation: Each line is stored in the form of a list.
Example 5: Reading file line by line using loop
File Content ([Link])
Dog
Cat
Horse
Cow
Code
file = open("[Link]", "r")
for line in file:
print(line)
[Link]()
Output
Dog
Cat
Horse
Cow
Explanation: A loop reads and prints one line at a time, which is useful for handling large files.
Example 6: Reading File Using Loop (Removing Extra Line Issue)
When we read a file line by line using a for loop, each line already contains a newline character (\n). At the
same time, the print() function also adds an extra newline by default. Because of this, an extra blank line
appears in the output. To fix this issue, we use strip() or end="".
Input File ([Link])
Dog
Cat
Horse
Cow
Code
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
Output
Dog
Cat
Horse
Cow
Explanation: The for loop reads the file line by line.
Each line contains a hidden \n (newline character).
strip() removes extra spaces and newline characters from both ends of the line.
This produces a clean and properly formatted output.
Alternative Code (without using strip)
file = open("[Link]", "r")
for line in file:
print(line, end="")
[Link]()
Output
Dog
Cat
Horse
Cow
Explanation: end="" prevents print() from adding an extra newline.
This also fixes the extra line issue and gives clean output.
2. File Mode: w (Write Mode) in Python
The w mode (write mode) in Python is used to write data into a file. If the file already exists, it will delete
(overwrite) all existing content and write new data. If the file does not exist, Python will create a new file
automatically.
This mode is mainly used when we want to create a new file or replace old data with new data.
Syntax:
file_object = open("file_name", "w")
OR (Recommended)
with open("file_name", "w") as file_object:
Examples of w Mode (Write Mode)
Example 1: Writing data into a new file
Code
file = open("[Link]", "w")
[Link]("Hello Students")
[Link]()
Output ([Link] file content)
Hello Students
Explanation: File is opened in write mode.
Since file is new, it is created automatically.
Data is written using write().
Old content (if any) is deleted.
Example 2: Overwriting existing file data
Input File ([Link] before running code)
Old Data: Python Basics
Code
file = open("[Link]", "w")
[Link]("New Data: File Handling in Python")
[Link]()
Output ([Link] after running code)
New Data: File Handling in Python
Explanation: Existing data is completely removed.
New data replaces old content.
Example 3: Writing multiple lines using \n
Code
file = open("[Link]", "w")
[Link]("Line 1: Apple\n")
[Link]("Line 2: Banana\n")
[Link]("Line 3: Mango")
[Link]()
Output
Line 1: Apple
Line 2: Banana
Line 3: Mango
Explanation: \n is used to move content to next line.
Multiple write() statements store multiple lines.
Example 4: Using with open() (Best method)
Code
with open("[Link]", "w") as file:
[Link]("Python is powerful")
Output
Python is powerful
Explanation: No need to use close().
File automatically closes after block ends.
Example 5: Writing numeric data (converted to string)
Code
file = open("[Link]", "w")
[Link](str(100))
[Link]("\n")
[Link](str(200))
[Link]()
Output
100
200
Explanation: Numbers must be converted into string using str().
Otherwise Python will give error.
\n is used for new line.
3. File Mode: a (Append Mode) in Python
The a mode (append mode) in Python is used to add new data at the end of an existing file. It does not delete
or overwrite the existing content. If the file does not exist, Python will create a new file automatically.
This mode is mainly used when we want to continuously add data like logs, records, or updates.
Syntax
file_object = open("file_name", "a")
OR (Recommended)
with open("file_name", "a") as file_object:
Examples of a Mode (Append Mode)
Example 1: Adding data to an existing file
Input File ([Link] before running code)
Hello Students
Code
file = open("[Link]", "a")
[Link]("\nWelcome to Python")
[Link]()
Output ([Link] after running code)
Hello Students
Welcome to Python
Explanation: Existing content is NOT deleted.
New data is added at the end of the file.
\n is used to move to a new line.
Example 2: Appending multiple lines
Code
file = open("[Link]", "a")
[Link]("\nLine 1: Apple")
[Link]("\nLine 2: Banana")
[Link]("\nLine 3: Mango")
[Link]()
Output
Hello Students
Welcome to Python
Line 1: Apple
Line 2: Banana
Line 3: Mango
Explanation: Each write() adds new content at the end.
Old data remains safe.
Example 3: Using with open() (Best method)
Code
with open("[Link]", "a") as file:
[Link]("\nPython is easy to learn")
Output
Hello Students
Welcome to Python
Python is easy to learn
Explanation: File automatically closes after execution.
Safer and cleaner method.
Example 4: Creating a new file using append mode
Code
file = open("[Link]", "a")
[Link]("This is a new file created using append mode")
[Link]()
Output ([Link])
This is a new file created using append mode
Explanation: If file does not exist, it is created automatically.
Then data is written inside it.
Example 5: Appending data in loop
Code
file = open("[Link]", "a")
for i in range(1, 4):
[Link](f"\nRecord {i}")
[Link]()
Output
Hello Students
Welcome to Python
Record 1
Record 2
Record 3
Explanation: Loop is used to add multiple records.
Each iteration appends new data at the end.
4. File Mode: r+ (Read and Write Mode) in Python
The r+ mode in Python is used to both read and write in an existing file. It means we can read the old content
and also modify it. However, the important point is that the file must already exist, otherwise Python will
give an error.
In this mode, writing starts from the beginning of the file, so if we are not careful, it can overwrite existing
data.
Syntax:
file_object = open("file_name", "r+")
OR (Recommended)
with open("file_name", "r+") as file_object:
Examples of r+ Mode (Read and Write Mode)
Example 1: Reading and then writing in a file
Input File ([Link] before running code)
Hello Students
Welcome to Python
Code
file = open("[Link]", "r+")
print([Link]())
[Link]("\nFile handling is important")
[Link]()
Output ([Link] after running code)
Hello Students
Welcome to Python
File handling is important
Explanation: First, file content is read using read().
Then new text is added at the end (cursor moves after reading).
Existing data remains and new data is added.
Example 2: Overwriting content using r+
Input File ([Link] before running code)
Python Basics
Learn File Handling
Code
file = open("[Link]", "r+")
[Link]("Java Basics")
[Link]()
Output ([Link] after running code)
Java Basics
Learn File Handling
Explanation: Writing starts from the beginning.
Old content gets partially overwritten.
Example 3: Reading partial content and writing
Input File ([Link])
Apple Banana Mango Orange
Code
file = open("[Link]", "r+")
print([Link](5))
[Link]("Fruit")
[Link]()
Output
Apple
Apple Banana Mango OrangeFruit
Explanation: First 5 characters are read → "Apple"
Then writing starts after reading position
New word "Fruit" is added
Example 4: Using with open() in r+ mode
Code
with open("[Link]", "r+") as file:
content = [Link]()
print(content)
[Link]("\nNew Line Added")
Output
(prints file content)
Updated File Content
(original content)
New Line Added
Explanation: File is read first.
New data is added at the end.
File closes automatically.
Example 5: r+ mode with pointer movement
Input File
Hello World
Code
file = open("[Link]", "r+")
[Link](6)
[Link]("Python")
[Link]()
Output (file content)
Hello Python
Explanation: seek(6) moves cursor after "Hello "
"World" gets replaced with "Python"
5. File Mode: w+ (Write and Read Mode) in Python
The w+ mode in Python is used to write and read a file at the same time. In this mode, if the file already
exists, its old content is completely deleted (overwritten). If the file does not exist, Python will create a new
file automatically.
This mode is mainly used when we want to create fresh data, write into it, and then read it in the same
program.
Syntax:
file_object = open("file_name", "w+")
OR (Recommended)
with open("file_name", "w+") as file_object:
Examples of w+ Mode (Write and Read Mode)
Example 1: Writing and then reading file content
Code
file = open("[Link]", "w+")
[Link]("Hello Students")
[Link](0)
print([Link]())
[Link]()
Output
Hello Students
Explanation: File is opened in w+ mode.
write() stores data in file.
seek(0) moves cursor back to start (important step).
read() reads the written content.
Example 2: Overwriting old file data
Input File ([Link] before running code)
Old Data: Python Basics
Code
file = open("[Link]", "w+")
[Link]("New Data: File Handling")
[Link](0)
print([Link]())
[Link]()
Output
New Data: File Handling
Explanation: Old data is completely removed.
New data is written.
Then file is read again.
Example 3: Writing multiple lines and reading
Code
file = open("[Link]", "w+")
[Link]("Line 1: Apple\n")
[Link]("Line 2: Banana\n")
[Link]("Line 3: Mango")
[Link](0)
print([Link]())
[Link]()
Output
Line 1: Apple
Line 2: Banana
Line 3: Mango
Explanation: Multiple lines are written using \n.
seek(0) is used to reset cursor.
Then full content is read.
Example 4: Using with open() in w+ mode
Code
with open("[Link]", "w+") as file:
[Link]("Python is powerful")
[Link](0)
print([Link]())
Output
Python is powerful
Explanation: File is automatically closed after block execution.
No need to use close().
Example 5: Writing numbers and reading them
Code
file = open("[Link]", "w+")
[Link]("100\n200\n300")
[Link](0)
print([Link]())
[Link]()
Output
100
200
300
Explanation: Numbers are converted into text format.
File is read after resetting pointer using seek(0).
6. File Mode: a+ (Append and Read Mode) in Python
The a+ mode in Python is used to append (add) new data to a file and also read the file content. In this mode,
existing data is never deleted. New data is always added at the end of the file.
If the file does not exist, Python will create a new file automatically.
One important point is that when we want to read after writing, we often need to use seek(0) to move the
cursor back to the beginning of the file.
Syntax:
file_object = open("file_name", "a+")
OR (Recommended)
with open("file_name", "a+") as file_object:
Examples of a+ Mode (Append and Read Mode)
Example 1: Appending data and reading file
Input File ([Link] before running code)
Hello Students
Code
file = open("[Link]", "a+")
[Link]("\nWelcome to Python")
[Link](0)
print([Link]())
[Link]()
Output
Hello Students
Welcome to Python
Explanation: Old data is preserved.
New data is added at the end.
seek(0) is used to read from the beginning.
Example 2: Creating new file using a+ mode
Code
file = open("[Link]", "a+")
[Link]("This is first line")
[Link](0)
print([Link]())
[Link]()
Output
This is first line
Explanation: File is created automatically if it does not exist.
Data is written and then read.
Example 3: Adding multiple lines
Code
file = open("[Link]", "a+")
[Link]("\nLine 1: Apple")
[Link]("\nLine 2: Banana")
[Link](0)
print([Link]())
[Link]()
Output
Hello Students
Welcome to Python
Line 1: Apple
Line 2: Banana
Explanation: Each write() adds new data at the end.
Old data remains safe.
Full file is read after seek(0).
Example 4: Using with open() in a+ mode
Code
with open("[Link]", "a+") as file:
[Link]("\nPython is easy")
[Link](0)
print([Link]())
Output
(Existing file content)
Python is easy
Explanation: File is automatically closed after execution.
New data is appended and file is read.
Example 5: Appending numbers and reading
Code
file = open("[Link]", "a+")
[Link]("\n100\n200\n300")
[Link](0)
print([Link]())
[Link]()
Output
(existing content)
100
200
300
Explanation: Numbers are added as text.
Old data remains unchanged.
seek(0) allows reading full file content.
7. File Mode: rb (Read Binary Mode) in Python
The rb mode (read binary mode) in Python is used to read files in binary format. In this mode, data is read in
the form of bytes instead of normal text. It is mainly used for files like images, videos, audio files, PDFs, and
other non-text files.
Unlike normal r mode, rb does not convert data into readable characters—it shows raw binary data.
Syntax:
file_object = open("file_name", "rb")
OR (Recommended)
with open("file_name", "rb") as file_object:
Examples of rb Mode (Read Binary Mode)
Example 1: Reading a text file in binary mode
Input File ([Link])
Hello Students
Code
file = open("[Link]", "rb")
content = [Link]()
print(content)
[Link]()
Output
b'Hello Students'
Explanation: Data is read in binary format (bytes).
b' ' shows that output is in binary form.
Example 2: Using with open() in rb mode
Code
with open("[Link]", "rb") as file:
content = [Link]()
print(content)
Output
b'Hello Students'
Explanation: File is automatically closed.
Output is shown in binary format.
Example 3: Reading image file in binary mode
Code
file = open("[Link]", "rb")
content = [Link](10)
print(content)
[Link]()
Output
b'\xff\xd8\xff\xe0\x00\x10JFIF'
Explanation: Image file is read as bytes.
Only first 10 bytes are displayed.
Example 4: Checking file type using rb mode
Code
file = open("[Link]", "rb")
data = [Link]()
print(type(data))
[Link]()
Output
<class 'bytes'>
Explanation: Binary data is stored as bytes type in Python.
Example 5: Reading partial binary data
Code
file = open("[Link]", "rb")
print([Link](5))
[Link]()
Output
b'Hello'
Explanation: Only first 5 bytes are read from file.
Useful for large files like images or videos.
8. File Mode: wb (Write Binary Mode) in Python
The wb mode (write binary mode) in Python is used to write data into a file in binary format. In this mode,
data is stored as bytes instead of normal text. It is mainly used for images, videos, audio files, PDFs, and
other non-text files.
If the file already exists, its old content is completely deleted (overwritten). If the file does not exist, Python
will create a new file automatically.
Syntax:
file_object = open("file_name", "wb")
OR (Recommended)
with open("file_name", "wb") as file_object:
Examples of wb Mode (Write Binary Mode)
Example 1: Writing text in binary mode
Code
file = open("[Link]", "wb")
[Link](b"Hello Students")
[Link]()
Output ([Link] content)
Hello Students (stored in binary format)
Explanation: b" " means data is written in byte format.
File is created and text is stored as binary data.
Old data (if any) is deleted.
Example 2: Using with open() in wb mode
Code
with open("[Link]", "wb") as file:
[Link](b"Python File Handling")
Output
(Python File Handling stored as binary data)
Explanation: File is automatically closed after writing.
Data is stored in byte format.
Example 3: Writing numeric data in binary mode
Code
file = open("[Link]", "wb")
[Link](str(100).encode())
[Link]()
Output
100 (in binary format)
Explanation: Numbers must be converted to string first.
.encode() converts string into bytes.
Example 4: Creating a binary file
Code
file = open("[Link]", "wb")
[Link](b"This is a new binary file")
[Link]()
Output
(Binary file created with given data)
Explanation: A new binary file is created.
Data is stored in byte format.
Example 5: Writing image data (concept example)
Code
image = open("[Link]", "rb")
data = [Link]()
[Link]()
file = open("[Link]", "wb")
[Link](data)
[Link]()
Output
Image file copied successfully
Explanation: First image is read in binary mode.
Then data is written into another file.
This is how file copying works in binary mode.
9. File Mode: ab (Append Binary Mode) in Python
The ab mode (append binary mode) in Python is used to add data at the end of a file in binary format. In this
mode, existing data is never deleted, it is only extended. If the file does not exist, Python will create a new
binary file automatically.
It is mainly used for images, videos, audio files, logs, or any binary data where we want to keep old data safe
and add new data continuously.
Syntax:
file_object = open("file_name", "ab")
OR (Recommended)
with open("file_name", "ab") as file_object:
Examples of ab Mode (Append Binary Mode):
Example 1: Appending binary text data
Code
file = open("[Link]", "ab")
[Link](b"\nHello Students")
[Link]()
Output ([Link] content)
(existing binary data)
Hello Students (added at end in binary form)
Explanation: b"" means data is written in binary format.
New data is added at the end without deleting old content.
Example 2: Using with open() in ab mode
Code
with open("[Link]", "ab") as file:
[Link](b"\nPython is powerful")
Output
(existing content)
Python is powerful
Explanation: File is automatically closed after execution.
Data is appended safely at the end.
Example 3: Appending numeric data in binary
Code
file = open("[Link]", "ab")
[Link](str(200).encode())
[Link]()
Output
(existing data)
200 (in binary format)
Explanation: Number is converted to string first.
.encode() converts it into binary format.
Then it is appended to file.
Example 4: Appending multiple lines in binary
Code
file = open("[Link]", "ab")
[Link](b"\nLine 1: Apple")
[Link](b"\nLine 2: Banana")
[Link]()
Output
(existing content)
Line 1: Apple
Line 2: Banana
Explanation: Each write() adds new binary data.
Old data remains unchanged.
Example 5: Appending image data (concept example)
Code
image = open("[Link]", "rb")
data = [Link]()
[Link]()
file = open("[Link]", "ab")
[Link](data)
[Link]()
Output
Image data appended to backup file
Explanation: Image is read in binary mode.
Same image data is appended to another file.
Used in backup systems.
10. File Mode: rb+ (Read and Write Binary Mode) in Python
The rb+ mode in Python is used to read and write a file in binary format at the same time. In this mode, the
file is opened as a binary file, so data is handled in bytes form instead of normal text.
The important condition is that the file must already exist, otherwise Python will give an error. This mode is
mainly used when we want to read binary data (like images, videos, PDFs) and also modify it.
Syntax:
file_object = open("file_name", "rb+")
OR (Recommended)
with open("file_name", "rb+") as file_object:
Examples of rb+ Mode (Read and Write Binary Mode)
Example 1: Reading and writing binary text data
Input File ([Link] before running code)
Hello Students
Code
file = open("[Link]", "rb+")
print([Link]())
[Link](b"\nWelcome")
[Link]()
Output ([Link] after running code)
b'Hello Students'
(existing content)
Welcome
Explanation: File is read in binary format using rb+.
Existing content is displayed in bytes form.
New data is appended in binary format.
Example 2: Overwriting part of binary file
Input File ([Link])
Python Basics
Code
file = open("[Link]", "rb+")
[Link](b"Java")
[Link]()
Output ([Link] after running code)
Java Basics
Explanation: Writing starts from the beginning of file.
Old content gets partially overwritten.
Example 3: Reading full binary file and modifying
Input File
Apple Banana Mango
Code
file = open("[Link]", "rb+")
data = [Link]()
print(data)
[Link](b" Orange")
[Link]()
Output
b'Apple Banana Mango'
Updated File Content
Apple Banana Mango Orange
Explanation: File is first read completely.
Then new binary data is added at the end.
Example 4: Using seek() in rb+ mode
Input File
Hello World
Code
file = open("[Link]", "rb+")
[Link](6)
[Link](b"Python")
[Link]()
Output (file content)
Hello Python
Explanation: seek(6) moves cursor after "Hello ".
"World" is replaced with "Python".
Example 5: Using with open() in rb+ mode
Code
with open("[Link]", "rb+") as file:
content = [Link]()
print(content)
[Link](b"\nFile Updated")
Output
(existing binary content)
Explanation: File is read first.
New data is added.
File is automatically closed.
Writing a File in Python (File Handling)
Writing a file in Python means storing data permanently into a file so that it can be used later. In file
handling, writing is one of the most important operations because it allows programs to save information
instead of losing it after execution ends. For example, if we store student marks, user details, or logs of a
system, we use file writing.
When we write data into a file, Python first opens the file using a specific mode like w (write mode) or a
(append mode). Then data is inserted into the file using writing methods. After writing, the file is closed to
ensure that all data is properly saved. If the file is opened in write mode (w), then old data is deleted and new
data is stored. But in append mode (a), new data is added at the end without removing old content.
Writing files is very useful in real-life applications such as saving user registration details, creating reports,
storing logs, and maintaining records in systems.
Methods of Writing a File in Python: Python provides two main methods for writing data into a file:
1. write() Method in Python (File Handling): The write() method in Python is used to write data into a file
as a single string. It stores exactly what we pass inside it. One important point is that write() does not
automatically move to a new line after writing data. So, if we want multiple lines, we must manually use \n.
This method is very useful when we want to write simple text, sentences, or controlled formatted data into a
file. It is commonly used in write mode (w) and append mode (a).
Syntax:
[Link]("text")
Examples of write() Method:
Example 1: Writing simple text into file
Code
file = open("[Link]", "w")
[Link]("Hello Students")
[Link]()
Input File
(empty file)
Output File
Hello Students
Explanation: A simple string is written into the file using write().
Example 2: Writing multiple lines using \n
Code
file = open("[Link]", "w")
[Link]("Line 1\nLine 2\nLine 3")
[Link]()
Input File
(empty file)
Output File
Line 1
Line 2
Line 3
Explanation: \n is used manually to move text to a new line.
Example 3: Overwriting existing file content
Input File (before execution)
Old Data: Python Basics
Code
file = open("[Link]", "w")
[Link]("New Data: File Handling")
[Link]()
Output File
New Data: File Handling
Explanation: Old content is deleted and replaced with new content because of w mode.
Example 4: Writing numbers (converted to string)
Code
file = open("[Link]", "w")
[Link](str(100))
[Link]("\n")
[Link](str(200))
[Link]()
Input File
(empty file)
Output File
100
200
Explanation: Numbers must be converted into string before writing.
Example 5: Writing sentence in append mode
Code
file = open("[Link]", "a")
[Link]("\nPython is very easy")
[Link]()
Input File (before execution)
Hello Students
Output File
Hello Students
Python is very easy
Explanation: New data is added at the end without deleting old content.
2. writelines() Method in Python (File Handling): The writelines() method in Python is used to write
multiple lines (a list of strings) into a file at once. It takes a list of strings as input and writes them into the
file one by one.
One important point is that writelines() does not automatically add a new line (\n) after each string. So, if we
want each item on a new line, we must manually include \n inside each string.
This method is very useful when we want to store multiple records, lists, or bulk data into a file efficiently.
Syntax
[Link](["text1", "text2", "text3"])
Examples of writelines() Method
Example 1: Writing list of strings into file
Code
file = open("[Link]", "w")
[Link](["Apple\n", "Banana\n", "Mango\n"])
[Link]()
Input File
(empty file)
Output File
Apple
Banana
Mango
Explanation: A list of strings is written into the file, and \n is used for new lines.
Example 2: Without using \n (wrong format case)
Code
file = open("[Link]", "w")
[Link](["Apple", "Banana", "Mango"])
[Link]()
Output File
AppleBananaMango
Explanation: Since \n is not used, all words are written in a single line.
Example 3: Writing student names
Code
file = open("[Link]", "w")
students = ["Rahul\n", "Aman\n", "Priya\n", "Sonia\n"]
[Link](students)
[Link]()
Output File
Rahul
Aman
Priya
Sonia
Explanation: A list variable is used to store multiple names and written into file.
Example 4: Writing numbers as strings
Code
file = open("[Link]", "w")
numbers = ["100\n", "200\n", "300\n"]
[Link](numbers)
[Link]()
Output File
100
200
300
Explanation: Numbers are written as strings with newline characters.
Example 5: Appending multiple lines using writelines()
Code
file = open("[Link]", "a")
[Link](["\nPython\n", "Java\n", "C++\n"])
[Link]()
Input File (before execution)
Programming Languages:
Output File
Programming Languages:
Python
Java
C++
Explanation: New data is added at the end of the file without deleting old content.
Reading from a File in Python (File Handling)
Reading from a file in Python means accessing and displaying the data stored inside a file. It is one of the
most important operations in file handling because it allows a program to retrieve previously saved
information.
When a file is opened in read mode (r) or other read-supported modes like r+ or rb, Python can extract data
from it. Reading is useful when we want to view, process, or reuse stored data such as student records, logs,
or configuration details.
In simple terms, writing stores data in a file, and reading brings that data back into the program.
Syntax:
file = open("file_name", "r")
data = [Link]()
[Link]()
OR (Best Practice)
with open("file_name", "r") as file:
data = [Link]()
Methods Used for Reading a File
read() → Reads the entire file at once
for loop → Reads file line by line
Examples of Reading from a File:
Example 1: Reading full file content using read()
Code
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Input File ([Link])
Hello Students
Welcome to Python
File Handling is easy
Output
Hello Students
Welcome to Python
File Handling is easy
Explanation: The read() method reads the entire file content at once and displays it.
Example 2: Using with open()
Code
with open("[Link]", "r") as file:
print([Link]())
Output
Hello Students
Welcome to Python
File Handling is easy
Explanation: The file is automatically closed after reading, making this method safer.
Example 3: Reading file line by line using loop
Code
file = open("[Link]", "r")
for line in file:
print([Link]())
[Link]()
Input File
Apple
Banana
Mango
Orange
Output
Apple
Banana
Mango
Orange
Explanation: Each line is read one by one using a loop, and strip() removes extra newline characters.
Example 4: Reading partial content
Code
file = open("[Link]", "r")
print([Link](10))
[Link]()
Input File
Hello Python Students
Output
Hello Pyth
Explanation: read(10) reads only the first 10 characters from the file.
Example 5: Reading and processing file data
Code
file = open("[Link]", "r")
data = [Link]()
words = [Link]()
print(words)
[Link]()
Input File
Python is very easy to learn
Output
['Python', 'is', 'very', 'easy', 'to', 'learn']
Explanation: The file content is split into individual words and stored in a list.
Methods of Reading a File in Python:
1. read(): The read() method in Python is used to read the entire content of a file at once. It is one of the
simplest and most commonly used file reading methods.
When a file is opened in read mode (r), the read() method extracts all the data stored inside the file and
returns it as a single string. After reading, the file pointer moves to the end of the file.
This method is useful when we want to display or process the complete file content in one go. However, it is
not recommended for very large files because it loads the entire file into memory.
Syntax:
[Link]()
OR
data = [Link]()
Examples of read() Method:
Example 1: Reading full file content
Code
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
Input File ([Link])
Hello Students
Welcome to Python
File Handling is easy
Output
Hello Students
Welcome to Python
File Handling is easy
Explanation: The read() method reads the entire file content at once and stores it in a variable.
Example 2: Using with open()
Code
with open("[Link]", "r") as file:
print([Link]())
Output
Hello Students
Welcome to Python
File Handling is easy
Explanation: The file is automatically closed after reading.
Example 3: Reading limited characters
Code
file = open("[Link]", "r")
print([Link](10))
[Link]()
Input File
Hello Python Students
Output
Hello Pyth
Explanation: read(10) reads only the first 10 characters of the file.
Example 4: Reading file into a variable
Code
file = open("[Link]", "r")
data = [Link]()
print("File Content:")
print(data)
[Link]()
Input File
Python is powerful
File handling is important
Output
File Content:
Python is powerful
File handling is important
Explanation: File content is stored in a variable and then printed.
Example 5: Processing data using read()
Code
file = open("[Link]", "r")
data = [Link]()
words = [Link]()
print(words)
[Link]()
Input File
Python is very easy to learn
Output
['Python', 'is', 'very', 'easy', 'to', 'learn']
Explanation: The file content is converted into a list of words using split().
2. readline(): The readline() method in Python is used to read a file one line at a time. It reads only the first
line initially, and every time it is called again, it moves to the next line of the file.
This method is useful when we want to process a file line by line, especially when working with structured
data like student records, logs, or lists.
Unlike read() which reads the whole file at once, readline() gives one line per call, making it more memory
efficient for large files.
Syntax:
[Link]()
OR
line = [Link]()
Examples of readline() Method:
Example 1: Reading first line of a file
Code
file = open("[Link]", "r")
line = [Link]()
print(line)
[Link]()
Input File ([Link])
Hello Students
Welcome to Python
File Handling is easy
Output
Hello Students
Explanation: readline() reads only the first line of the file.
Example 2: Reading multiple lines using multiple readline() calls
Code
file = open("[Link]", "r")
print([Link]())
print([Link]())
print([Link]())
[Link]()
Output
Hello Students
Welcome to Python
File Handling is easy
Explanation: Each readline() call reads the next line of the file.
Example 3: Using readline() in loop
Code
file = open("[Link]", "r")
line = [Link]()
while line:
print([Link]())
line = [Link]()
[Link]()
Input File
Apple
Banana
Mango
Orange
Output
Apple
Banana
Mango
Orange
Explanation: Loop continues until all lines are read one by one.
Example 4: readline() with empty line handling
Code
file = open("[Link]", "r")
print([Link]())
print([Link]())
[Link]()
Input File
Python
Java
C++
Output
Python
Java
Explanation: If there is an empty line, readline() still moves line by line including blank lines.
Example 5: readline() with strip()
Code
file = open("[Link]", "r")
line = [Link]()
print([Link]())
[Link]()
Input File
Hello World
Output
Hello World
Explanation: strip() removes extra newline (\n) from the output.
3. readlines(): The readlines() method in Python is used to read all the lines of a file at once and store them
in a list. Each line of the file becomes an element of the list.
This method is very useful when we want to work with all lines together, but still keep them separated in list
form. Unlike read() (which returns a single string), readlines() returns a list of strings, where each string is
one line from the file.
Syntax:
[Link]()
OR
lines = [Link]()
Examples of readlines() Method:
Example 1: Reading all lines as a list
Code
file = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
Input File ([Link])
Hello Students
Welcome to Python
File Handling is easy
Output
['Hello Students\n', 'Welcome to Python\n', 'File Handling is easy\n']
Explanation: Each line is stored as a separate element in a list, including \n.
Example 2: Printing each line from list
Code
file = open("[Link]", "r")
lines = [Link]()
for line in lines:
print([Link]())
[Link]()
Input File
Apple
Banana
Mango
Orange
Output
Apple
Banana
Mango
Orange
Explanation: Loop is used to print each line separately and strip() removes extra newline.
Example 3: Accessing specific line using index
Code
file = open("[Link]", "r")
lines = [Link]()
print(lines[0])
print(lines[2])
[Link]()
Input File
Python
Java
C++
JavaScript
Output
Python
C++
Explanation: Since data is stored in a list, we can access lines using index.
Example 4: Counting number of lines in a file
Code
file = open("[Link]", "r")
lines = [Link]()
print("Total lines:", len(lines))
[Link]()
Input File
Line 1
Line 2
Line 3
Line 4
Output
Total lines: 4
Explanation: len() function is used to count number of lines in the list.
Example 5: Removing newline characters from all lines
Code
file = open("[Link]", "r")
lines = [Link]()
clean_lines = []
for line in lines:
clean_lines.append([Link]())
print(clean_lines)
[Link]()
Input File
Red
Green
Blue
Yellow
Output
['Red', 'Green', 'Blue', 'Yellow']
Explanation: strip() removes \n, and cleaned data is stored in a new list.
Play with the File Pointer in Python (File Handling):
In Python file handling, the file pointer is a cursor that keeps track of the current position inside a file.
Whenever we read or write data, Python uses this pointer to know where the next operation will happen.
By default:
When a file is opened, the pointer is at the beginning of the file
After reading or writing, the pointer moves automatically
We can manually control this pointer using special methods like seek() and tell()
This concept is called “playing with the file pointer”, because we can move it forward, backward, or
check its position as needed.
Important Method to Control File Pointer:
1. tell()
The tell() method in Python is used to find the current position of the file pointer (cursor) inside a file.
When a file is opened, Python uses a pointer to track where the next read or write operation will happen. As
we read or write data, this pointer automatically moves forward.
The tell() method helps us know the exact position of the pointer in bytes. It is useful for tracking how much
data has been read or where the next operation will occur.
In simple words: tell() shows “where the file pointer is currently located.”
Syntax:
[Link]()
Examples of tell() Method:
Example 1: Basic use of tell() after reading
Code
file = open("[Link]", "r")
print([Link](5))
print("Pointer position:", [Link]())
[Link]()
Input File
Hello Python
Output
Hello
Pointer position: 5
Explanation: After reading 5 characters, the pointer moves to position 5.
Example 2: tell() after reading full file
Code
file = open("[Link]", "r")
[Link]()
print([Link]())
[Link]()
Input File
Hello World
Output
11
Explanation: After reading the full file, the pointer reaches the end.
Example 3: tell() after partial read
Code
file = open("[Link]", "r")
[Link](3)
print([Link]())
[Link]()
Input File
ABCDE
Output
3
Explanation: After reading 3 characters, the pointer moves to position 3.
Example 4: Checking pointer before and after reading
Code
file = open("[Link]", "r")
print("Start position:", [Link]())
[Link](4)
print("After reading:", [Link]())
[Link]()
Input File
Python
Output
Start position: 0
After reading: 4
Explanation: Initially, pointer is at 0. After reading 4 characters, it moves to position 4.
Example 5: tell() with readline()
Code
file = open("[Link]", "r")
line = [Link]()
print([Link]())
print("Pointer position:", [Link]())
[Link]()
Input File
Line1
Line2
Output
Line1
Pointer position: 6
Explanation: After reading the first line, the pointer moves forward including the newline character.
Example 6: Multiple reads with tell()
Code
file = open("[Link]", "r")
[Link](2)
print([Link]())
[Link](3)
print([Link]())
[Link]()
Input File
HelloWorld
Output
2
5
Explanation: The pointer keeps updating after every read operation.
2. seek()
The seek() method in Python is used to move the file pointer (cursor) to a specific position inside a file.
When a file is opened, Python starts reading or writing from the beginning by default. But sometimes we
need to jump to a particular position in the file. For this purpose, we use seek().
In simple words: seek() = move the file pointer to a given location
This method is very useful when we want to re-read data, skip data, or access specific parts of a file directly.
Syntax:
[Link](position)
Parameters
position → The byte number where the pointer should move
Important Point
seek(0) → moves pointer to the start of the file
After seek(), reading/writing starts from the new position
Examples of seek() Method:
Example 1: Moving pointer to start of file
Code
file = open("[Link]", "r")
[Link](5)
[Link](0)
print([Link]())
[Link]()
Input File
Hello Python
Output
Hello Python
Explanation: Pointer was moved back to the start using seek(0) and file is read again.
Example 2: Reading from a specific position
Code
file = open("[Link]", "r")
[Link](6)
print([Link]())
[Link]()
Input File
Hello Python
Output
Python
Explanation: Pointer moves to position 6, so reading starts from "Python".
Example 3: seek() with tell()
Code
file = open("[Link]", "r")
print("Start:", [Link]())
[Link](4)
print("After seek:", [Link]())
[Link]()
Input File
ABCDE12345
Output
Start: 0
After seek: 4
Explanation: seek() changes pointer position, and tell() verifies it.
Example 4: Partial reading after seek()
Code
file = open("[Link]", "r")
[Link](2)
print([Link](3))
[Link]()
Input File
HelloWorld
Output
llo
Explanation: Pointer moves to position 2 and reads next 3 characters.
Example 5: Resetting file pointer
Code
file = open("[Link]", "r")
print([Link](5))
[Link](0)
print([Link](5))
[Link]()
Input File
Python
Output
Pytho
Pytho
Explanation: Pointer is reset to start using seek(0).
Example 6: Multiple seek positions
Code
file = open("[Link]", "r")
[Link](3)
print([Link]())
[Link](1)
print([Link]())
[Link]()
Input File
ABCDEFGHIJ
Output
3
1
Explanation: Pointer is moved to different positions and checked using tell().
Important Method to Control File Pointer: seek() in Python:
The seek() method in Python is used to change (move) the position of the file pointer (cursor) within a file.
When we open a file, Python starts reading or writing from the beginning of the file (position 0). But
sometimes we don’t want to read from the start—we may want to jump to a specific position. For this
purpose, we use seek().
This method is very important in file handling because it allows random access to a file, meaning we can
directly go to any position instead of reading everything step by step.
In simple words: seek() = move file pointer to a specific location
Syntax (Original and Standard)
[Link](offset, whence)
Parameters
offset → Number of bytes to move
whence → Starting point (optional)
0 → Beginning of file (default)
1 → Current position
2 → End of file
Examples of seek() Method:
Example 1: Move pointer from start (seek(0))
Code
file = open("[Link]", "r")
[Link](5)
[Link](0)
print([Link]())
[Link]()
Input File
Hello Python
Output
Hello Python
Explanation: Pointer was moved back to the beginning using seek(0) and file is read again.
Example 2: Jump to specific position
Code
file = open("[Link]", "r")
[Link](6)
print([Link]())
[Link]()
Input File
Hello Python
Output
Python
Explanation: Pointer moves to position 6, so reading starts from "Python".
Example 3: seek() with tell()
Code
file = open("[Link]", "r")
print("Start position:", [Link]())
[Link](4)
print("After seek:", [Link]())
[Link]()
Input File
ABCDE12345
Output
Start position: 0
After seek: 4
Explanation: tell() shows pointer position before and after using seek().
Example 4: Reading after seek()
Code
file = open("[Link]", "r")
[Link](2)
print([Link](3))
[Link]()
Input File
HelloWorld
Output
llo
Explanation: Pointer moves to position 2 and reads next 3 characters.
Example 5: Reset pointer and re-read
Code
file = open("[Link]", "r")
print([Link](5))
[Link](0)
print([Link](5))
[Link]()
Input File
Python
Output
Pytho
Pytho
Explanation: seek(0) resets pointer to start so data can be read again.
Example 6: Using whence (advanced concept)
Code
file = open("[Link]", "rb")
[Link](2, 0)
print([Link]())
[Link]()
Input File
ABCDE
Output
CDE
Explanation: seek(2, 0) means move 2 bytes from the start of file.
Example 7: seek() from current position (whence = 1)
Code
file = open("[Link]", "rb")
[Link](3)
[Link](2, 1)
print([Link]())
[Link]()
Input File
ABCDEFGH
Output
DEFGH
Explanation: First 3 characters are read → pointer moves forward
Then seek(2, 1) moves pointer 2 steps ahead from current position
Reading starts from new position
Example 8: seek() from end of file (whence = 2)
Code
file = open("[Link]", "rb")
[Link](-3, 2)
print([Link]())
[Link]()
Input File
ABCDEFGH
Output
FGH
Explanation: seek(-3, 2) means move 3 bytes back from end
Reading starts from that position
Example 9: Writing after seek() (overwrite case)
Code
file = open("[Link]", "r+")
[Link](6)
[Link]("XYZ")
[Link]()
Input File (before)
Hello Python
Output File (after)
Hello XYZhon
Explanation: Pointer moves to position 6
"Python" starts getting overwritten by "XYZ"
Example 10: Reset and re-read full file
Code
file = open("[Link]", "r")
[Link](4)
[Link](3)
[Link](0)
print([Link]())
[Link]()
Input File
PythonFile
Output
PythonFile
Explanation: Pointer is reset using seek(0)
Full file is read again from start
Example 11: Checking pointer movement step by step
Code
file = open("[Link]", "r")
print([Link]())
[Link](2)
print([Link]())
[Link](5)
print([Link]())
[Link]()
Input File
ABCDEFGHIJ
Output
0
2
5
Explanation: tell() shows pointer position at each step
seek() moves pointer manually
Example 12: seek() in binary file handling
Code
file = open("[Link]", "rb")
[Link](4)
print([Link](3))
[Link]()
Input File
123456789
Output
567
Explanation: Works same in binary mode
Reads 3 bytes starting from position 4
Important Methods to Control File Pointer: seek() with tell() in Python
The seek() method in Python is used to move the file pointer (cursor) to a specific position inside a file.
While reading or writing a file, Python automatically moves the pointer forward. But sometimes we need to
manually change the position of the pointer, and that is done using seek().
In simple words:
seek() = move the pointer to a specific location
tell() = show current pointer position
Both are often used together to understand and control file movement.
Syntax
[Link](position)
position is the byte location where you want to move the pointer.
Examples of seek() and tell()
Example 1: Moving pointer to start using seek(0)
Code
file = open("[Link]", "r")
[Link](5)
print("Before seek:", [Link]())
[Link](0)
print("After seek:", [Link]())
[Link]()
Input File
Hello Python
Output
Before seek: 5
After seek: 0
Explanation: Pointer was at 5 after reading, then moved back to start using seek(0).
Example 2: Reading from a specific position
Code
file = open("[Link]", "r")
[Link](6)
print([Link]())
[Link]()
Input File
Hello Python
Output
Python
Explanation: Pointer is moved to position 6, so reading starts from "Python".
Example 3: seek() + tell() together
Code
file = open("[Link]", "r")
print("Start position:", [Link]())
[Link](4)
print("After seek:", [Link]())
[Link]()
Input File
ABCDE12345
Output
Start position: 0
After seek: 4
Explanation: Pointer starts at 0 and moves to 4 using seek().
Example 4: Reading after moving pointer
Code
file = open("[Link]", "r")
[Link](2)
print([Link](3))
[Link]()
Input File
HelloWorld
Output
llo
Explanation: Pointer moves to position 2, then reads next 3 characters.
Example 5: Resetting pointer using seek()
Code
file = open("[Link]", "r")
print([Link](5))
[Link](0)
print([Link](5))
[Link]()
Input File
Python
Output
Pytho
Pytho
Explanation: Pointer is reset to start using seek(0) and file is read again.
Example 6: Multiple seek operations
Code
file = open("[Link]", "r")
[Link](3)
print([Link]())
[Link](1)
print([Link]())
[Link]()
Input File
ABCDEFGHIJ
Output
3
1
Explanation: Pointer is moved to different positions using seek() and verified using tell().
CSV File Handling in Python
What is a CSV File?
A CSV (Comma-Separated Values) file is a simple text file used to store data in a table format. Each line in
the file represents one record, and the values in that line are separated by commas.
In real life, we often work with table-like data such as student records, employee details, or sales data. A
CSV file is an easy way to store this type of data without using complex systems like databases.
Since it is a plain text file, it can be opened in many applications like Excel, Notepad, and programming
languages like Python. This makes CSV files very flexible and widely used.
Example:
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
The first row is called the header (column names)
Each next row contains data of one student
Comma (,) separates each value
Why CSV Files are Useful?
Simple and easy to understand
Lightweight (does not take much space)
Can be opened anywhere (Excel, Notepad, Python)
Easy to share between systems
Need of CSV File Handling in Python
In Python, CSV file handling is important when we want to store, manage, and reuse data in a simple way
without using databases.
In real-life programs, we often deal with data like:
1. Student records
2. Employee details
3. Marks and results
4. Sales data
If we do not store this data in a file, it will be lost when the program stops. CSV files help us save this data
permanently.
Example Use Case
Suppose you are making a student record system.
Name,Age,Marks
Aman,20,85
Riya,19,90
Now your Python program can:
Read student data
Display it
Add new students
Update marks
This makes your program useful in real life.
Why Use CSV in Python?
1. Easy for beginners
2. No need for complex database setup
3. Python provides a built-in csv module
4. Data can be easily converted into lists or dictionaries
CSV File Handling in Python: CSV (Comma-Separated Values) file handling in Python refers to the
process of reading data from a CSV file and writing data into it using Python programs. A CSV file is a
simple text file that stores data in a tabular format where each row represents a record and each value is
separated by a comma. These files are widely used because they are easy to create, understand, and share
between different applications like Excel and programming languages. In real-world scenarios, data such as
student details, employee records, or sales information is often stored in CSV files because they provide a
simple alternative to complex databases.
1. CSV File Content (Before Reading)
📄 Suppose we have a file named [Link]
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
This is the actual data stored in the file.
First row = column names (header)
Remaining rows = student records
Comma ( , ) separates values
Reading CSV Files in Python: Reading a CSV file means accessing the data stored inside it so that it can be
used in a program. In Python, this is done using the built-in csv module, which makes the process simple and
efficient. When we use [Link](), Python reads the file line by line and automatically separates the values
at commas, converting each row into a list. This makes it easy to access individual elements using index
positions.
For example, consider a CSV file named [Link] that contains the following data:
Name,Age,Marks
Aman,20,85
Riya,19,90
When we read this file using Python:
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
the output will be:
['Name', 'Age', 'Marks']
['Aman', '20', '85']
['Riya', '19', '90']
This shows that each row is converted into a list, making it easier to process the data programmatically.
Reading CSV Files Using Dictionary: Another useful method is [Link](), which reads each row as
a dictionary instead of a list. In this case, the column names become keys, and the corresponding values
become dictionary values. This approach improves readability because we can access data using meaningful
names instead of index numbers.
For example:
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row["Name"], row["Marks"])
Here, instead of using positions like row[0], we directly use column names like "Name" and "Marks", which
makes the code easier to understand, especially for beginners.
Writing CSV Files in Python: Writing a CSV file means storing data into the file in a structured tabular
format. In Python, this is done using [Link](). We can write one row at a time using [Link]() or
multiple rows using [Link](). While writing, it is important to open the file in write mode and use
newline='' to prevent extra blank lines from appearing in the file.
For example:
import csv
with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](["Name", "Age", "Marks"])
[Link](["Aman", 20, 85])
This code creates or overwrites a CSV file and stores the given data in a proper table format.
Writing CSV Files Using Dictionary: Python also provides [Link]() to write data in dictionary
form. In this method, we define the column names and then provide data as key-value pairs. This ensures that
the data is well-organized and easy to understand.
For example:
import csv
with open("[Link]", "w", newline='') as file:
fields = ["Name", "Age", "Marks"]
writer = [Link](file, fieldnames=fields)
[Link]()
[Link]({"Name": "Aman", "Age": 20, "Marks": 85})
This method is especially useful when working with structured data in real-world applications.
CSV File Handling in Python:
1. CSV File Content (Before Reading)
📄 Suppose we have a file named [Link]
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
This is the actual data stored in the file.
First row = column names (header)
Remaining rows = student records
Comma ( , ) separates values
2. Writing Data into CSV File
Code:
import csv
with open("[Link]", "w", newline='') as file:
writer = [Link](file)
[Link](["Name", "Age", "Marks"])
[Link](["Aman", 20, 85])
[Link](["Riya", 19, 90])
[Link](["Rahul", 21, 78])
Output (File Content):
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
Explanation: This program creates a CSV file and stores data in rows. Each [Link]() adds one row
to the file.
3. Reading CSV File (Basic Method)
Code:
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
Output:
['Name', 'Age', 'Marks']
['Aman', '20', '85']
['Riya', '19', '90']
['Rahul', '21', '78']
Explanation: Python reads each row and converts it into a list. Commas are automatically separated.
4. Reading Specific Data (Index Method)
Code:
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
next(reader) # skip header
for row in reader:
print("Name:", row[0], "Marks:", row[2])
Output:
Name: Aman Marks: 85
Name: Riya Marks: 90
Name: Rahul Marks: 78
Explanation: We skip the header row and access data using index numbers.
5. Reading CSV using DictReader
Code:
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
Output:
{'Name': 'Aman', 'Age': '20', 'Marks': '85'}
{'Name': 'Riya', 'Age': '19', 'Marks': '90'}
{'Name': 'Rahul', 'Age': '21', 'Marks': '78'}
Explanation: Each row becomes a dictionary where column names act as keys.
Example:
print(row["Name"])
6. Appending New Data into CSV File
Code:
import csv
with open("[Link]", "a", newline='') as file:
writer = [Link](file)
[Link](["Karan", 22, 88])
Updated File Output:
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
Karan,22,88
Explanation: Append mode ("a") adds new data without deleting old records.
CSV File Handling – Important Extra Concepts
CSV file handling in Python is not only about reading and writing data, but also about understanding some
important internal behaviors that affect how data is stored and displayed. These small concepts are often
ignored by beginners, but they are very important for writing correct and clean programs. Let’s understand
them properly in detail.
1. Importance of newline='' in CSV Files
When we write data into a CSV file using Python, we often use:
open("[Link]", "w", newline='')
The newline='' parameter is very important because it controls how line breaks are handled while writing
data into the file. If we do not use this parameter, Python may add extra blank lines between rows in the CSV
file, especially when working on Windows systems.
Example of problem without newline='':
Sometimes the file may look like this:
Name,Age,Marks
Aman,20,85
Riya,19,90
These extra blank lines make the file look messy and unorganized.
Correct way:
with open("[Link]", "w", newline='') as file:
Explanation: CSV files are very sensitive to line breaks. The newline='' parameter ensures that Python
writes each row properly without inserting unnecessary empty lines. This keeps the file clean, structured, and
readable.
2. Difference Between [Link]() and [Link]()
Python provides two main ways to read CSV files, and understanding the difference between them is very
important.
[Link](): When we use [Link](), each row is converted into a list. The values are accessed using
index positions.
Example output:
['Aman', '20', '85']
Here:
row[0] → Name
row[1] → Age
row[2] → Marks
Explanation: This method is simple but not very readable because we need to remember index positions.
[Link](): When we use DictReader(), each row is converted into a dictionary where column names
become keys.
Example output:
{'Name': 'Aman', 'Age': '20', 'Marks': '85'}
Now we can access data like:
row["Name"]
Explanation: This method is more readable and professional because we use column names instead of index
numbers. It reduces confusion and makes the code easier to maintain.
3. Difference Between writerow() and writerows()
Another important concept is understanding how data is written into CSV files.
writerow(): This method is used to write one row at a time.
[Link](["Aman", 20, 85])
Explanation: Each call adds a single record to the file.
writerows(): This method is used to write multiple rows at once.
data = [
["Aman", 20, 85],
["Riya", 19, 90]
]
[Link](data)
Explanation: This is useful when we already have a list of multiple records and want to write them together
in one go. It saves time and reduces code length.
4. Skipping Header Row Using next():
CSV files usually contain a header row that defines column names. Sometimes we only want to process
actual data and ignore the header.
next(reader)
Explanation: The next() function moves the pointer to the next line in the file. When used once, it skips the
first row (header). This is useful when we only want to work with data records.
Skipping Header Row Using next() in CSV
Input CSV File ([Link])
First, let’s see what data is stored in the file:
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
In this file:
First row = Header (column names)
Remaining rows = Actual data
Python Code
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
next(reader) # skip header row
for row in reader:
print(row)
Output
['Aman', '20', '85']
['Riya', '19', '90']
['Rahul', '21', '78']
5. Data Type Issue in CSV Files:
One very important concept is that CSV files do not store data types. Everything in a CSV file is stored as a
string, even numbers.
For example:
row["Age"] = "20"
Even though it looks like a number, it is actually a string.
Problem:
If we try to do calculations:
row["Age"] + 5
It will give an error because string and integer cannot be added.
Solution:
We must manually convert the data type:
int(row["Age"]) + 5
Explanation: CSV files are simple text files, so they do not understand data types. Therefore, type
conversion is necessary when performing calculations.
Data Type Issue in CSV Files: CSV file handling in Python has one very important limitation: CSV files do
not store data types. This means that everything written inside a CSV file is stored as text (string), even if the
value looks like a number. This often creates confusion when we try to perform calculations on CSV data.
Example CSV File ([Link])
Name,Age,Marks
Aman,20,85
Riya,19,90
Rahul,21,78
Even though Age and Marks are numbers, they are actually stored as strings in CSV.
Reading CSV File in Python
import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row["Name"], row["Age"], row["Marks"])
Output:
Aman 20 85
Riya 19 90
Rahul 21 78
Important Observation
Even though Age and Marks look like numbers, Python reads them like this:
row = {
"Name": "Aman",
"Age": "20",
"Marks": "85"
}
Notice:
"20" is a string
"85" is a string
Problem (Data Type Issue): If we try to perform calculation directly:
print(row["Age"] + 5)
This will give an error because:
"20" is a string
5 is an integer
Python cannot add string + number
Error (Conceptual): TypeError: can only concatenate str (not "int") to str
Solution (Type Conversion Required): We must convert string into integer:
print(int(row["Age"]) + 5)
Output
25
6. Using with open() (Best Practice)
Instead of manually opening and closing files, we use:
with open("[Link]", "r") as file:
Explanation: This method automatically closes the file after the operation is completed. It prevents memory
leaks and ensures that data is safely saved. This is the safest and most recommended way to handle files in
Python.