0% found this document useful (0 votes)
12 views

File Handling -7

The document provides an overview of file handling in Python, covering the basics of reading and writing both binary and text files. It explains essential file operations, including opening, reading, writing, and closing files, as well as handling exceptions that may arise during these processes. Additionally, it discusses the importance of exception handling and provides examples of built-in exceptions and how to catch them in Python code.

Uploaded by

stalinking2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

File Handling -7

The document provides an overview of file handling in Python, covering the basics of reading and writing both binary and text files. It explains essential file operations, including opening, reading, writing, and closing files, as well as handling exceptions that may arise during these processes. Additionally, it discusses the importance of exception handling and provides examples of built-in exceptions and how to catch them in Python code.

Uploaded by

stalinking2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

FILE HANDLING

By
Prof. G.V.S.SARMA
Department of Chemical Engineering
Andhra University College of Engineering(A)

1
Contents
1. Introduction to File Handling

2. Writing and Reading Binary Data

3. Writing and Parsing Text Files

2
1. Introduction to File Handling

• File handling is a fundamental aspect of any programming


language, including Python.

• It enables a program to interact with files on the disk—whether


to read from them, write to them, or manipulate their
contents in various ways.

• Understanding file handling is crucial because it allows you to


manage data persistence, perform input/output operations, and
automate tasks that involve file processing.

3
Why File Handling is Important?

In many real-world applications, data needs to be stored and


retrieved from files. For instance:

Log Files: Storing logs of system or application activities.

Data Files: Reading and writing data for analysis or processing.

Configuration Files: Saving user settings or application


configurations.

Binary Files: Handling images, videos, or other non-text data.

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.

Basic File Operations

1. Opening a File:

◦ Before any operations can be performed on a file, it must be opened


using Python's open() function.

◦ This function takes two main arguments: the file name and the mode
in which the file is to be opened.

Example: file = open('example.txt', 'r')

This opens example.txt in read mode (r)


5
2. File Modes:

r : Read mode. Opens the file for reading. If the file does not exist, it raises an
error. This is the default mode

w: Write mode. Opens the file for writing (overwrites if it exists).

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.

r+ : Opens the file for both reading and writing

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().

Example: content = file.read()

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.

Example: file = open(‘firstfile.txt', 'w')

file.write(‘created my first file!')

7
5. Closing a File:

◦ After performing the desired operations, it is important to close the


file using the close() method. This ensures that all resources used by
the file are properly released.

Example: file.close()

◦ Alternatively, Python provides the ‘with’ statement for file handling,


which automatically closes the file once the block of code is executed:

Example: with open('example.txt', 'r') as file:

content = file.read()

print(content)

8
Types of Files:

1. Text Files: Files that contain plain text, usually encoded in


formats like ASCII or UTF-8. They are easy to create, read,
and edit. (UTF stands for Unicode Transformation Format)

2. Binary Files: Files that contain binary data, which may not
be human-readable. Examples include images, videos, and
executable files.

These files require specific modes and handling methods.

9
2. Writing and Reading Binary Data

• Binary data refers to data that is not in a human-readable text


format, such as images, audio files, or other types of data that require
specific encoding or decoding.

• Handling binary data involves working with bytes, which are sequences
of 8-bit values.

Writing Binary Data:

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.

Example: with open('example.bin', 'wb') as file:

data = b'\x00\x01\x02\x03\x04\x05\
x06\x07'

file.write(data)

In this example, example.bin is opened in binary write mode (wb),


and the data (a bytes object) is written to the file. The b prefix before
the string indicates that it is a bytes object.
11
2. Writing Structured Binary 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)

Here, struct.pack() is used to pack integers and a float into a


binary format before writing it to data.bin. The format string 'iif'
specifies the types (two integers and one float).

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.

1. Opening a File for Reading Binary Data:

◦ Use open() with the mode rb (read binary).

Example: with open('example.bin', ‘rb') as file:

data = file.read()

print(data)

This reads the entire content of example.bin as bytes and


prints it. The output will be the raw byte data.
13
2. Unpacking Structured Binary Data:

◦ If you packed the binary data using struct, you'll need to unpack it
using the same format.

Example: import struct


with open('data.bin', ‘rb') as file:
packed_data = file.read()
unpacked_data = struct.unpack('iif',
packed_data)
print(unpacked_data)

Here, struct.unpack() is used to convert the binary data back


into its original integer and float values. The format string 'iif'
must match the one used during packing.
14
3. Writing and Parsing Text Files

• Text files are simpler to handle than binary files because they contain
data encoded in a human-readable format.

• Python treats text files as sequences of characters, where each


character is typically one byte (in ASCII encoding) or more bytes (in
encodings like UTF-8).

Writing Text Files:

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.

Example: with open('example.txt', 'w', encoding='utf-8') as


file:

file.write('This is a line of text.\n')

file.write('This is another line of text.\n')

In this example, example.txt is opened in text write mode (w), and


two lines of text are written to the file. The encoding='utf-8'
argument ensures that the text is encoded in UTF-8.
16
2. Writing Multiple Lines:

◦ You can also write multiple lines at once using the writelines()
method, which takes a list of strings.

Example: lines = ['First line\n', 'Second line\n', 'Third line\n']

with open('example.txt', 'w', encoding='utf-8')


as file:

file.writelines(lines)

Here, writelines() is used to write a list of strings to example.txt.


Note that you need to include newline characters (\n) manually to
separate 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.

1. Reading the Entire File:

◦ The simplest way to read a text file is to read its entire content at
once.

Example: with open('example.txt', ‘r’, encoding='utf-8') as


file:

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.

Example: with open('example.txt', ‘r’, encoding='utf-8') as


file:

for line in file:

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:

◦ You can read specific parts of a file by using the readline() or


readlines() methods.

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:

• Commonly occurring exceptions are usually defined in the


compiler/interpreter. These are called built-in exceptions.
• Python’s standard library is an extensive collection of built-in
exceptions that deal with commonly occurring errors
(exceptions) by providing standardized solutions for such
errors.
• On the occurrence of any built-in exception, the appropriate
exception handler code is executed which displays the reason
along with the raised exception name.
22
Built-in Exception Description

1.SyntaxError It is raised when there is an error in the syntax of the


Python code

2. ValueError It is raised when a built-in method or operation receives


an argument that has the right data type but mismatched
or inappropriate values

3. IOError It is raised when the file specified in a program statement


cannot be opened.

4. KeyboardInterrupt It is raised when the user accidentally hits the Delete or


Esc key while executing a program due to which the
normal flow of the program is interrupted.

23
5. ModuleNotFoundError It is raised when the requested module definition is not
found.

6. EOFError It is raised when the end of file condition is reached


without reading any data by input().

7. ZeroDivisionError It is raised when the denominator in a division operation is


zero.

8. IndexError It is raised when the index or subscript in a sequence is


out of range.

9. NameError It is raised when a local or global variable name is not


defined.
24
10. IndentationError It is raised due to incorrect indentation in the program
code.

11. TypeError It is raised when an operator is supplied with a value of


incorrect data type.

12. OverFlowError It is raised when the result of a calculation exceeds the


maximum limit for numeric data type

25
Raising Exceptions:

• Each time an error is detected in a program, the Python


interpreter raises (throws) an exception.
• Exception handlers are designed to execute when a specific
exception is raised.
• Programmers can also forcefully raise exceptions in a
program using the raise and assert statements.
• Once an exception is raised, no further statement in the
current block of code is executed.
26
1. The raise Statement:

• The raise statement can be used to throw an exception.


• The syntax of raise statement is:
 raise exception-name[(optional argument)]
 The argument is generally a string that is displayed
when the exception is raised.
• The raise statement can be used to raise a built-in
exception or user-defined one.

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:

• Python categorizes exceptions into distinct types so that specific


exception handlers (code to handle that particular exception) can
be created for each type.
• Exception handlers separate the main logic of the program from
the error detection and correction code.
• The compiler or interpreter keeps track of the exact position
where the error has occurred.
• Exception handling can be done for both user-defined and built-in
exceptions.
32
Process of Exception Handling:

33
Catching Exceptions:

• An exception is said to be caught when a code that is


designed to handle a particular exception is executed.
• Exceptions, if any, are caught in the try block and
handled in the except block.
• While writing or debugging a program, a user might
doubt an exception to occur in a particular part of the
code. Such suspicious lines of codes are put inside a try
block.
34
• Every try block is followed by an except block.
• The appropriate code to handle each of the possible
exceptions (in the code inside the try block) is written inside
the except clause.
• You can handle multiple exceptions in a single ‘except’ block
or have multiple ‘except’ blocks.
• While executing the program, if an exception is
encountered, further execution of the code inside the try
block is stopped and the control is transferred to the except
block.
35
 The syntax of the try ... except clause is as follows:

1. try:

#code that might raise an exception

# If an exception occurs here, it jumps to the except block

except [exception-name]:

#code to handle the exception

2. try:

# code that might raise an exception

except (ExceptionType1, ExceptionType2) as e:

# code to handle either ExceptionType1 or ExceptionType2

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:

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))

except ValueError:

print("Error: Please enter valid integers.")

else:

result = num1 + num2

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

denom = int(input("Enter the denominator: "))

quotient = numerator / denom

print("Division performed successfully")

except ZeroDivisionError:

print("Denominator as ZERO is not allowed")

else:

print("The result of division operation is", quotient)

finally:

print("OVER AND OUT")


43
Custom Exceptions
 Custom exceptions in Python allow you to define your
exception classes, providing a way to create and raise
specific types of errors tailored to your application needs.
 This is particularly useful when you encounter situations in
your code that don’t fit standard built-in exceptions.
 Definition:

class FoundException(Exception):

pass
44
Usage of Custom Exception:

try:

for row, record in enumerate(table):

for column, field in enumerate(record):

for index, item in enumerate(field):

if item == target:

raise FoundException()

except FoundException:

print("found at ({0}, {1}, {2})".format(row, column, index))

else:

print("not found")

45
Explanation:

◦ The FoundException class is defined as a subclass of the built-in


Exception class. It’s a custom exception used for breaking out of
deeply nested loops

◦ 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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy