B.
Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
BCC 402: Python Programming
Unit 4: Python File Operations
Reading Files, Writing Files in Python, Understanding read functions, read(), readline(),
readlines(). Understanding write functions, write() and writelines(). Manipulating file pointer
using seek programming, using file operations.
Introduction
File handling refers to the process of performing operations on a file such as creating, opening,
reading, writing and closing it, through a programming interface. It involves managing the data
flow between the program and the file system on the storage device, ensuring that data is handled
safely and efficiently
Opening a File in Python
To open a file we can use open() function, which requires file path and mode as arguments:
This code opens file named file.txt.
File Modes in Python
When opening a file, we must specify the mode we want to which specifies what we want to do
with the file. Here’s a table of the different modes available.
Mode Description Behavior
Opens the file for reading. File must exist;
Read-only mode.
r otherwise, it raises an error.
Opens the file for reading binary data. File
Read-only in binary mode.
rb must exist; otherwise, it raises an error.
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
Mode Description Behavior
Opens the file for both reading and writing.
Read and write mode.
r+ File must exist; otherwise, it raises an error.
Opens the file for both reading and writing
Read and write in binary
binary data. File must exist; otherwise, it
mode.
rb+ raises an error.
Opens the file for writing. Creates a new file
Write mode.
w or truncates the existing file.
Opens the file for writing binary data.
Write in binary mode. Creates a new file or truncates the existing
wb file.
Opens the file for both writing and reading.
Write and read mode. Creates a new file or truncates the existing
w+ file.
Opens the file for both writing and reading
Write and read in binary
binary data. Creates a new file or truncates
mode.
wb+ the existing file.
Opens the file for appending data. Creates a
Append mode.
a new file if it doesn't exist.
Opens the file for appending binary data.
Append in binary mode.
ab Creates a new file if it doesn't exist.
Opens the file for appending and reading.
Append and read mode.
a+ Creates a new file if it doesn't exist.
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
Mode Description Behavior
Opens the file for appending and reading
Append and read in binary
binary data. Creates a new file if it doesn't
mode.
ab+ exist.
Creates a new file. Raises an error if the file
Exclusive creation mode.
x already exists.
Exclusive creation in binary Creates a new binary file. Raises an error if
xb mode. the file already exists.
Exclusive creation with Creates a new file for reading and writing.
x+ read and write mode. Raises an error if the file exists.
Exclusive creation with
Creates a new binary file for reading and
read and write in binary
writing. Raises an error if the file exists.
xb+ mode.
Closing a File
Closing a file is essential to ensure that all resources used by the file are properly released.
file.close() method closes the file and ensures that any changes made to the file are saved.
Using with Statement
with statement is used for resource management. It ensures that file is properly closed after its suite
finishes, even if an exception is raised. with open() as method automatically handles closing the
file once the block of code is exited, even if an error occurs. This reduces the risk of file corruption
and resource leakage.
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
Reading from a text file
We can write a program to read the contents of a file. Before reading a file, we must make sure
that the file is opened in “r”, “r+”, “w+” or “a+” mode. There are three ways to read the contents
of a file:
The read() method: This method is used to read a specified number of bytes of data from a
data file.
Syntax: file_object.read(n)
If no argument or a negative number is specified in read(), the entire file content is read.
Example:
The readline() method: This method reads one complete line from a file where each line
terminates with a newline (\n) character. It can also be used to read a specified number (n) of bytes
of data from a file but maximum up to the newline character (\n).
Syntax: file_object.readline(n)
Example:
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
To read the entire file line by line using the readline(), we can use a loop. This process is known
as looping/iterating over a file object. It returns an empty string when EOF is reached.
Example:
The readlines() method: The method reads all the lines and returns the lines along with newline
as a list of strings.
Syntax: file_object.readlines(n)
Example:
In case we want to display each word of a line separately as an element of a list, then we can use
split() function.
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
Writing to a Text File
For writing to a file, we first need to open it in write or append mode. If we open an existing file
in write mode, the previous data will be erased, and the file object will be positioned at the
beginning of the file. On the other hand, in append mode, new data will be added at the end of the
previous data as the file object is at the end of the file. After opening the file, we can use the
following methods to write data in the file.
• write() - for writing a single string
• writelines() - for writing a sequence of strings
The write() method: write() method takes a string as an argument and writes it to the text file. It
returns the number of characters being written on single execution of the write() method. Also, we
need to add a newline character (\n) at the end of every sentence to mark the end of line.
Syntax: file_object.write(string)
Example:
The writelines() method: This method is used to write multiple strings to a file. We need to pass
an iterable object like lists, tuple, etc. containing strings to the writelines() method.
Syntax: file_object.writelines(sequence)
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
Example:
File pointers
A file pointer in Python is like a cursor that keeps track of the current position within a file. This
position determines where the next read or write operation will occur. When a file is opened, the
file pointer is usually positioned at the beginning of the file (0th byte).
tell(): The tell() method returns the current file position in a file stream.
Syntax: file_object.tell()
Example:
seek(): The Python File seek() method sets the file's pointer at a specified position in the current
file. A file's pointer is used to store the current position of the read and write operations in a file,
and this method can move the file pointer forward or backward.
For instance, whenever we open a file to read from it, the file pointer is always positioned at 0. It
is gradually incremented as we progress through the content of the file. But some scenarios require
the file to be read from a particular position in the file. This is where this method comes into play.
Syntax: file_object.seek(offset[, whence])
Parameters
• offset − This is the number of positions of the read/write pointer to move within the file.
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
• whence − (Optional) It defaults to 0; which means absolute file positioning, other values are 1
which means seek relative to the current position and 2 means seek relative to the file's end.
Example:
Output:
B. Tech-III SEM / BCC402: Python Programming/ UNIT – IV / Python File Operations
Kavish Tomar / Assistant Professor / Department of CSE / JMS Institute of Technology-Ghaziabad
IMPORTANT QUESTIONS
Q1. There is a file named Input.Txt. Enter some positive numbers into the file named Input.Txt.
Read the contents of the file and if it is an odd number write it to ODD.TXT and if the number
is even, write it to EVEN.TXT.
Q2. Discuss File I/O in Python. How to perform open, read, write and close into a file? Write
a Python program to read a file line-by-line store it into a variable.
Q3. Explain the use of “with” construct in Python with an example program.
Q4. Change all the numbers in the file to text. Construct a program for the same.
Example:
Given 2 integer numbers, return their product only if the product is equal to or lower
than 10.
And the result should be:
Given two integer numbers, return their product only if the product is equal to or
lower than one zero.
Q5. Construct a program which accepts a sequence of words separated by whitespace as file
input. Print the words composed of digits only.
Q6. Construct a program to change the contents of the file by reversing each character
separated by comma:
Hello!!
Output
H,e,l,l,o,!,!
Q7. Write a python program to copy contents from one file to another.
Q8. Write a Pyton Program to find te longest word in a file. Get the file name from the user.