Unit - 4
Unit - 4
File Handling in Python: File handling in Python involves interacting with files on your computer to read data from them
or write data to them. Python provides several built-in functions and methods for creating, opening, reading, writing,
and closing files.
Opening a File in Python: To perform any file operation, the first step is to open the file. Python's built-in open()
function is used to open files in various modes, such as reading, writing, and appending. The syntax for opening a file in
Python is −
Where, filename is the name of the file to open and mode is the mode in which the file is opened (e.g., 'r' for reading, 'w'
for writing, 'a' for appending).
r:
1
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb
2 Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the
default mode.
r+
3
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
4
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for
writing.
b
6
Opens the file in binary mode
t
7
Opens the file in text mode (default)
8 +
open file for updating (reading and writing)
wb
9 Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates
a new file for writing.
w+
10 Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
wb+
11 Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
a
12 Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file for writing.
ab
13 Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a new file for writing.
a+
14 Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file
opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+
15 Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
x
16
open for exclusive creation, failing if the file already exists
Once a file is opened and you have one file object, you can get various information related to that file.
Example 1
Example 2
In here, we are opening a file named "foo.txt" in binary write mode ("wb"), printing its name, whether it's closed, and its
opening mode, and then closing the file −
# Open a file
fo = open("foo.txt", "wb")
fo.close()
Opening mode: wb
Reading a File in Python: Reading a file in Python involves opening the file in a mode that allows for reading, and then
using various methods to extract the data from the file. Python provides several methods to read data from a file −
In the following example, we are using the read() method to read the whole file into a single string −
content = file.read()
print(content)
Welcome to Python!!!
In here, we are using the readline() method to read one line at a time, making it memory efficient for reading large files
line by line −
line = file.readline()
while line:
print(line, end='')
line = file.readline()
Hello!!!
Welcome to Python!!!
Now, we are using the readlines() method to read the entire file and splits it into a list where each element is a line −
lines = file.readlines()
print(line, end='')
Hello!!!
Welcome to Python!!!
Writing to a File in Python: Writing to a file in Python involves opening the file in a mode that allows writing, and then
using various methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When opening a file in write mode ('w'), the file's existing
content is erased.
In this example, we are using the write() method to write the string passed to it to the file. If the file is opened in 'w'
mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will append the string to the end of the
file −
file.write("Hello, World!")
In here, we are using the writelines() method to take a list of strings and writes each string to the file. It is useful for
writing multiple lines at once −
file.writelines(lines)
Closing a File in Python: We can close a file in Python using the close() method. Closing a file is an essential step in file
handling to ensure that all resources used by the file are properly released. It is important to close files after operations
are completed to prevent data loss and free up system resources.
Example
In this example, we open the file for writing, write data to the file, and then close the file using the close() method −
file.write("This is an example.")
file.close()
The with statement is a best practice in Python for file operations because it ensures that the file is automatically closed
when the block of code is exited, even if an exception occurs.
Example
In this example, the file is automatically closed at the end of the with block, so there is no need to call close() method
explicitly −
When performing file operations, it is important to handle potential exceptions to ensure your program can manage
errors gracefully.
In Python, we use a try-finally block to handle exceptions when closing a file. The "finally" block ensures that the file is
closed regardless of whether an error occurs in the try block −
try:
finally:
file.close()
File Method: A file object is created using open() function. The file class defines the following methods with which
different file IO operations can be done. The methods can be used with any file like object such as byte stream or
network stream.
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2
Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
file.fileno()
3 Returns the integer file descriptor that is used by the underlying implementation to request I/O operations
from the operating system.
file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.
file.next()
5
Returns the next line from the file each time it is being called.
6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
file.readline([size])
7
Reads one entire line from the file. A trailing newline character is kept in the string.
file.readlines([sizehint])
8 Reads until EOF using readline() and return a list containing the lines. If the optional sizehint argument is
present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after
rounding up to an internal buffer size) are read.
file.seek(offset[, whence])
9
Sets the file's current position
file.tell()
10
Returns the file's current position
file.truncate([size])
11
Truncates the file's size. If the optional size argument is present, the file is truncated to (at most) that size.
file.write(str)
12
Writes a string to the file. There is no return value.
file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a
list of strings.
Python File seek() Method: The Python File seek() method sets the file's cursor at a specified position in the current file.
A file's cursor is used to store the current position of the read and write operations in a file; and this method can move
this file cursor forward or backward.
For instance, whenever we open a file to read from it, the file cursor 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 picture.
If the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it remains
useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets causes
undefined behaviour.
All file objects are seekable.
Syntax
fileObject.seek(offset[, whence])
Parameters
offset − This is the number of positions of the read/write pointer to move within the file.
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.
Return Value: This method does not return any value. It just sets the cursor at the specified offset.
Example
The following example shows the usage of the Python File seek() method. We are trying to set the pointer at the
beginning of the file. Hence, we pass the offset argument as 0 to this method.
# Open a file
fo = open("foo.txt", "r+")
line = fo.readline()
fo.seek(0, 0)
line = fo.readline()
fo.close()
Example
The new position of the pointer can also be set relative to its current position in the file. To do that, we must always
open the file in the binary mode: it can either be in reading binary or writing binary modes. Then, we are passing the
number of positions to move from the current position as the offset argument and the value 1 as the whence argument
to the method.
# Open a file
fo = open("foo.txt", "rb")
fo.seek(18, 1)
line = fo.read()
fo.close()
The output produced after executing the given program will be in the binary form. But it can be decoded into a string
using the decode() method.
File Contents: b'This is 2nd line\r\nThis is 3rd line\r\nThis is 4th line\r\nThis is 5th line'
Example
However, in some cases we need the pointer to be set at the ending of the file; such as appending information to an
existing file using the read and write (r+) mode. Let us see an example below demonstrating the same on a file named
"foo.txt".
# Open a file
fo = open("foo.txt", "r+")
fo.seek(0, 2)
fo.seek(0, 0)
line = fo.read()
fo.close()
Once we compile and run the program above, the output is produced as follows −
Example
As we have already discussed above, the file's cursor can also move backwards from the end of the file; or from a certain
position. In the given example, we are opening a file "foo.txt" in the reading binary (rb) mode. The file cursor is set at the
end of file by passing the whence argument as 2 and by passing negative values as the offset parameter to the method,
we are trying to move the file cursor backwards.
# Open a file
fo = open("foo.txt", "rb")
fo.seek(-36, 2)
line = fo.read()
fo.close()
If we compile and run the program above, the file contents are read from the end of file up to the given number of
positions.
Example
The tell() method goes hand-in-hand with the seek() method. In the following example, we are trying to use the seek()
method to set the file cursor at a specific position and then, use the tell() method to retrieve this position set.
# Open a file
fo = open("foo.txt", "r")
fo.seek(18, 0)
line = fo.read()
#Using tell() method retrieve the cursor position from the ending