File Handling -7
File Handling -7
By
Prof. G.V.S.SARMA
Department of Chemical Engineering
Andhra University College of Engineering(A)
1
Contents
1. Introduction to File Handling
2
1. Introduction to File Handling
3
Why File Handling is Important?
4
Python provides a straightforward way to handle files using built-in
functions and methods. The process involves opening a file, performing
the required operations (read/write), and then closing the file to free up
system resources.
1. Opening a File:
◦ This function takes two main arguments: the file name and the mode
in which the file is to be opened.
r : Read mode. Opens the file for reading. If the file does not exist, it raises an
error. This is the default mode
a: Append mode. Opens the file for appending data at the end.
b: Binary mode. Used for binary files like images. This can be combined with
other modes, like rb or wb.
w+: Opens the file for writing and reading. If the file does not exist a
new file is created
a+: Opens the file for reading and appending. If the file already exists
the data is appended. If the file does not exist it creates a new file
6
3. Reading from a File:
◦ Once a file is opened in read mode, its contents can be read using
methods like read(), readline(), or readlines().
print(content)
4. Writing to a File:
◦ When a file is opened in write or append mode, you can write data to
it using the write() or writelines() methods.
7
5. Closing a File:
Example: file.close()
content = file.read()
print(content)
8
Types of Files:
2. Binary Files: Files that contain binary data, which may not
be human-readable. Examples include images, videos, and
executable files.
9
2. Writing and Reading Binary Data
• Handling binary data involves working with bytes, which are sequences
of 8-bit values.
When you write binary data to a file, you are writing raw bytes. This is
different from writing text, where Python automatically encodes the text
using a specified encoding (like UTF-8). For binary files, no such
encoding takes place
10
1. Opening a File for Writing Binary Data:
◦ Use the open() function with the mode wb (write binary). This
mode ensures that you can write bytes directly to the file.
data = b'\x00\x01\x02\x03\x04\x05\
x06\x07'
file.write(data)
◦ For more complex binary data, you might need to pack the data
into a specific structure before writing it. The struct module in
Python is often used for this purpose.
Example: import struct
with open('data.bin', 'wb') as file:
packed_data = struct.pack('iif', 1, 2, 3.14)
file.write(packed_data)
12
Reading Binary Data:
Reading binary data is the reverse process of writing. You open the file
in binary read mode (rb) and read the bytes back.
data = file.read()
print(data)
◦ If you packed the binary data using struct, you'll need to unpack it
using the same format.
• Text files are simpler to handle than binary files because they contain
data encoded in a human-readable format.
Writing to text files involves opening the file in a mode that allows
writing (w for writing, a for appending) and then writing strings to the
file.
15
1. Opening a File for Writing Text:
◦ Use open() with the mode w (write) or a (append) and specify the
encoding if necessary.
◦ You can also write multiple lines at once using the writelines()
method, which takes a list of strings.
file.writelines(lines)
17
Parsing Text Files:
Parsing a text file involves reading its content and processing it line by
line or in chunks. This is useful for tasks like extracting specific
information, processing log files, or reading configuration settings.
◦ The simplest way to read a text file is to read its entire content at
once.
content = file.read()
print(content)
18
2. Reading the File Line by Line:
◦ For larger files or when you need to process each line separately,
reading the file line by line is more efficient.
print(line.strip())
In this example, the file is read line by line. The strip() method is
used to remove leading and trailing whitespace, including the
newline character at the end of each line.
19
3. Reading Specific Parts of a File:
Example:
with open('example.txt', ‘r’, encoding='utf-8') as file:
first_line = file.readline()
print('First line:', first_line.strip())
remaining_lines = file.readlines()
print('Remaining lines:', [line.strip() for line in remaining_lines])
readline() reads a single line, and readlines() reads all the remaining
lines, returning them as a list of strings.
20
Exceptions
Even if a statement or expression is syntactically correct, there
might arise an error during its execution.
For example, trying to open a file that does not exist, division by
zero and so on.
Such types of errors might disrupt the normal execution of the
program and are called Exceptions.
“An exception is a Python object that represents an error”.
When an error occurs during the execution of a program, an
exception is said to have been raised.
21
Built-in Exceptions:
23
5. ModuleNotFoundError It is raised when the requested module definition is not
found.
25
Raising Exceptions:
27
28
The assert Statement:
• An assert statement in Python is used to test an expression
in the program code.
• If the result after testing comes false, then the exception is
raised.
• This statement is generally used in the beginning of the
function or after a function call to check for valid input.
• The syntax for assert statement is:
assert Expression[,arguments]
29
• On encountering an assert statement, Python evaluates the expression
given immediately after the assert keyword.
• If this expression is false, an AssertionError exception is raised which
can be handled like any other exception.
30
Exception handling
Exception handling is a mechanism to deal
with errors or exceptional situations that may
occur during the execution of a program.
Exception handling is being used not only in
Python programming but in most
programming languages like C++, Java, Ruby,
etc. 31
Need for Exception Handling:
33
Catching Exceptions:
1. try:
except [exception-name]:
2. try:
36
Example:
try:
num1 = int(input("Enter a numerator: "))
num2 = int(input("Enter a denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter valid integers.")
37
‘try…except...else’ block:
We can put an optional else clause along with the try...except clause.
An except block will be executed only if some exception is raised in
the try block.
But if there is no error then none of the except blocks will be
executed.
In this case, the statements inside the else clause will be executed.
38
The syntax of the try ... except … else clause is as
follows:
try:
# code that might raise an exception
except ExceptionType:
# code to handle the exception
else:
# code to execute if no exception occurred
39
Example:
try:
except ValueError:
else:
print("Sum:", result)
40
finally’ block:
The try statement in Python can also have an optional finally
clause.
The statements inside the finally block are always executed
regardless of whether an exception has occurred in the try
block or not.
It is a common practice to use the finally clause while working
with files to ensure that the file object is closed.
If used, finally should always be placed at the end of the try
clause, after all except blocks and the else block.
41
The syntax of the finally clause is as follows:
try:
# code that might raise an exception
except ExceptionType:
# code to handle the exception
finally:
# code that will always execute,
regardless of exceptions
42
Example:
try:
numerator = 50
except ZeroDivisionError:
else:
finally:
class FoundException(Exception):
pass
44
Usage of Custom Exception:
try:
if item == target:
raise FoundException()
except FoundException:
else:
print("not found")
45
Explanation:
◦ Inside the nested loops, if a condition is met (in this case, if ‘item’ is
equal to ‘target’), the ‘FoundException’ is raised, causing the
control flow to jump to the ‘except’ block.
◦ In the ‘except’ block, the program prints the position where the
item was found.
◦ If the exception is not raised (i.e. the item is not found), then the
‘else’ block is executed, printing “not found”.
46
Benefits:
◦ Using a custom exception simplifies the code by reducing the
number of nested ‘if’ statements and ‘break’ statements
needed to exit from nested loops.
◦ It improves nested code readability by clearly indicating the
purpose of the exception and the point where it is raised.
◦ The use of custom exception encapsulates the error-handling
logic, making the code more modular and easier to maintain.
47
THANK YOU
48