I.M.C.A Semester – 3 Data Science Fundamentals With Python Unit – 5
Files and Exception Handling
Contents
File handling in Python refers to the process of
working with files, which includes tasks such as creating, reading, writing,
updating, and deleting files.
Python provides built-in functions and libraries
that make it easy to perform various file-related operations.
File handling is crucial for working with data
persistence, configuration files, text processing, and more in Python programs.
Here are some key aspects of file handling in
Python:
1.
Opening a File:
To work with a file, you first need to open it
using the open() function. This function takes two arguments: the file name or
path and the mode in which you want to open the file.
Common modes include:
r: Read (default) - Opens the file for reading.
w: Write - Opens the file for writing. If the file
already exists, its truncated (emptied). If it doesnt exist, a new file is
created.
a: Append - Opens the file for writing but does not
truncate it. New data is added at the end.
b: Binary - Indicates that the file should be treated
as a binary file (e.g., rb for reading a binary file).
2.
Reading from a File (Text Input):
Reading from a File is also called Text input. Text
input in file handling allows you to read and work with the content of text files
in your Python programs.
To read data from a text file, you first need to
open the file using the open() function with the r mode (read mode).
The r mode indicates that you intend to read from
the file.
After opening a file in read mode, you can read its
contents using methods like read(), readline(), and readlines().
read(): Reads the entire file as a single string.
readline(): Reads one line at a time and advances the file
pointer.
readlines(): Reads all lines into a list, with each line as an
element.
Following is a simple Example of Text Input in
python:
file = open(“File_name.txt”,”r”)
data = file.read()
print(data)
3. Writing to a File (Text Output):
Writing to a file is also called Text
Output. To write text data to a file, you need to open or create the file using
the open() function with the w mode (write mode).
If the file already exists, opening it
in w mode will truncate (empty) its contents. If the file does not exist, a new
file will be created.
After opening a file in write or append mode, you
can write data to the file using the write() method.
write(): Writes the specified data (usually strings) to the
file.
Following is a simple Example of Text Output in
python:
file = open("File_name.txt",w)
data = "Hello World \nThis is Text Output
Program"
file.write(data)
print("Text Saved Successfully")
file.close()
Output:
Text Saved Successfully
4.
Closing a File:
Its essential to close a file using the close()
method or the with statement to release system resources and ensure data
integrity.
The with statement is often used because it
automatically closes the file when the block is exited.
5.
Handling Exceptions:
When working with files, you should handle
exceptions that may occur, such as FileNotFoundError
(when trying to open a non-existent file) or PermissionError (insufficient permissions).
Using try-except blocks helps your program
gracefully handle file-related errors.
File dialog is very powerful feature for any
application or software that helps you to open and save files or directories.
File dialogs allow users to:
Select existing files or directories
Create new filenames
Select a location and name for a new file or
directory
Python Tkinter (and TK) offer a set of dialogs that
you can use when working with files. By using these you dont have to design
standard dialogs your self. Example dialogs include an open file dialog, a save
file dialog and many others.
Here Tkinter is an in-built GUI library provide by
python to develop desktop or windows application.
The tkinter filedialog provide various types of
file dialog functions such as:
· asksaveasfilename()
·
asksaveasfile()
·
askopenfilename()
·
askopenfile()
·
askdirectory()
·
askopenfilenames()
·
askopenfiles()
According to list of
functions we can say that filedialog is
one of the tkinter modules that provides classes and library functions to
create file/directory selection windows.
We can use filedialog where we need to ask the user to browse a file or
a directory from the system.
Following are some of the key tkinter file dialog
functions:
1.
filedialog.askopenfilename():
This function opens a file dialog that
allows the user to select a file for opening.
It
returns the path of the selected file as a string.
Example:
file_path = filedialog.askopenfilename()
2.
filedialog.asksaveasfilename():
This function opens a file dialog for
saving a file. It allows the user to specify a file name and location.
It returns the path where the user intends to
save the file as a string.
Example:
save_path
= filedialog.asksaveasfilename()
3.
filedialog.askopenfilenames():
This function is similar to
askopenfilename, but it allows the user to select multiple files.
It returns a tuple of file paths as strings.
Example:
file_paths = filedialog.askopenfilenames()
4.
filedialog.askdirectory():
This function opens a file dialog for
selecting a directory.
It
returns the path of the selected directory as a string.
Example:
dir_path
= filedialog.askdirectory()
These functions are part of the filedialog module
in tkinter, and they make it easy to incorporate file and directory selection
capabilities into your Python applications with a GUI.
You can use these functions in combination with
other tkinter widgets and elements to build more complex graphical user
interfaces that involve file manipulation.
Following is Common Example of open file dialog:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
filename = filedialog.askopenfilename()
print(filename)
root.mainloop()
Output:
D:/SYIMCA/filedialog.py
According
to above example Tk() is a class that is used to create an instance of a
tkinter frame. Tk() helps display the root window and manages all the
other components of the tkinter application.
filedialog is a
method of tkinter module that provide file dialog functions, here
askopenfilename() function is used to define open file dialog box.
The process of Retrieving data from web is also
known as web scrapping. It is the process of extracting information or data
from websites.
Retrieving data from web is a process that helps to
automatically access web pages, retrieve their content, and extract specific
data for various purposes.
It allows you to collect data from the web in a
structured and organized manner, making it accessible for analysis, storage, or
other applications.
Python provide two most important libraries that
can help you to perform web scrapping easily.
Retrieving data from an HTML document using Python
typically involves web scraping. this is the process of extracting specific
information from HTML or XML content.
You can use Python libraries such as requests to fetch web pages and another
library like Beautiful Soup to parse
and extract data from the HTML.
Heres a step-by-step guide on how to retrieve data
from HTML using Python:
1.
Import Necessary Libraries:
First, you need to import the required libraries.
You can install these libraries using pip if you havent already:
>>>
pip install requests
>>>
pip install bs4
Then, to check this library is successfully
installed or not, in your Python script, import the libraries as follows:
>>> import requests
>>> from bs4 import BeautifulSoup
2.
Send an HTTP Request:
Use the requests library to send an HTTP GET
request to the URL containing the HTML content you want to retrieve:
Example:
url =
https://google.com
response =
requests.get(url)
3.
Parse HTML Content:
Use
Beautiful Soup to parse the HTML content of the web page. This library helps
you navigate the HTML structure and extract specific data.
Initialize a BeautifulSoup object with the page
content and specify the parser you want to use (usually html.parser):
Example:
soup = BeautifulSoup(response.text, html.parser)
4.
Extract Data:
You can now use Beautiful Soup to extract specific
data from the HTML. You can find elements by their HTML tags, classes, or
attributes. For example, to extract all the links (<a> tags) from the
page, you can do this:
Example:
print(soup.a)
print(soup.prettify())
print(soup.status_code)
This is just one example. You can use a variety of
methods and filters to extract data that matches your specific needs.
Here soup.a
can return data of <a> tag, soup.prettify()
return whole data in proper structure and soup.status_code return 200 , which means request is successfully
completed.
5. Further
Processing and Storage:
You can use the extracted data for various purposes,
such as saving it to a file, performing analysis, or integrating it into other
parts of your application.
Thats the basic process for retrieving and
extracting data from HTML using Python. Web scraping is a powerful tool for
automating data collection from websites, but its essential to respect the
websites terms of service and legal considerations when scraping data from the
web.
Error in Python can be of two types i.e. Syntax
errors and Exceptions.
Errors are problems in a program due to which will
stop the program from execution.
On the other hand, exceptions are raised when some
internal events occur due to limitation of hardware or software part, which
change the normal flow of the program.
Following are some Different types of Exceptions which
are raised in python:
SyntaxError: This exception is raised when the interpreter
encounters a syntax error in the code, such as a misspelled keyword, a missing
colon, or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or
function is applied to an object of the wrong type, such as adding a string to
an integer.
NameError: This exception is raised when a variable or
function name is not found in the current scope.
IndexError: This exception is raised when an index is out of
range for a list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found
in a dictionary.
ValueError: This exception is raised when a function or method
is called with an invalid argument or input, such as trying to convert a string
to an integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or
method is not found on an object, such as trying to access a non-existent
attribute of a class instance.
IOError: This exception is raised when an I/O operation,
such as reading or writing a file, fails due to an input/output error.
FileNotFoundError: Raised when trying to open or manipulate a file
that does not exist.
ZeroDivisionError: This exception is raised when an attempt is made
to divide a number by zero.
ImportError: This exception is raised when an import statement
fails to find or load a module It returns ModuleNotFoundError
exception.
These exceptions can occur during the execution of
a Python program, such as division by zero, trying to access a non-existent
file, or attempting to use a variable that has not been defined.
Handling exceptions ensures that your program does
not crash and provides a way to handle these exceptional conditions in a controlled
manner.
In Python, exception handling is implemented using
a combination of the try, except, else,
and finally blocks.
1.
try block: This is where you place the code that
might raise an exception. Python will execute the code inside the try block,
and if an exception occurs, it will immediately jump to the appropriate except
block.
2.
except block:
This block is used to specify how to handle a specific type of exception. You
can have multiple except blocks to handle different exceptions. If an exception
of the specified type occurs inside the try block, the code in the
corresponding except block is executed. If no exception occurs, the except
block is skipped.
Example:
try:
x = 10
/ 0 # This will raise a ZeroDivisionError
except
ZeroDivisionError:
print("Division by zero is not allowed.")
Output:
Division by zero is not allowed.
3.
else block (optional): The
code inside the else block is executed only if no exceptions are raised within
the try block. It is typically used for code that should run when everything in
the try block is successful.
Example:
try:
a = 10
/ 2 # No exception here
except
ZeroDivisionError:
print("Division by zero is not allowed.")
else:
print("Division successful:", a)
Output:
Division successful: 5.0
4.
finally block (optional): The
code inside the finally block is executed regardless of whether an exception
occurred or not. It is often used for cleanup tasks, such as closing files or
releasing resources.
Example:
try:
file =
open("example.txt", "r")
#
Perform some file operations
except
FileNotFoundError:
print("File not found.")
finally:
file.close() # Ensure the file is
always closed
Output:
File not found.
Python provides a wide range of built-in exception
types for common errors, but you can also create custom exceptions by defining
your own exception classes. This allows you to raise and handle specific types
of exceptions in your code.
By using exception handling effectively, you can
make your Python programs more robust and reliable by dealing with unexpected
errors.
An exception in Python is an event that occurs
during the execution of a program that disrupts the normal flow of
control. Exceptions can be caused by a variety of factors, such as syntax
errors, logical errors, and runtime errors.
Python Provide the concept of raising Exception in
program using raise keyword. It allows you to throw an exception at any
time.
Python raise Keyword is used to raise
exceptions or errors. The raise keyword raises an error and stops the control
flow of the program.
Raising an exception refers to the process of
intentionally creating an error condition in your code to handle unexpected
situations or errors gracefully.
When an exception is raised, it interrupts the
normal flow of the program and looks for a matching exception handler (also
known as an exception catcher) to handle the error. If no appropriate handler
is found, the program terminates.
Following is a syntax to raise an exception:
try:
if
condition:
raise Exception_name
else:
#code
except
Exception_name:
#code
According to above syntax we can raise
an Exception according to our programs need by place it with conditional
statement.
Following is a simple example of raise exception:
no = int(input("Enter Number
Between 1 to 10 = "))
try:
if no <= 1 or no >= 10:
raise Exception
print("Your Number =
",no)
except Exception:
print("Exception is Handle
Please Input Number Between Range...")
print("Program End")
Output:
Enter Number Between 1 to 10 = 12
Exception is Handle Please Input Number
Between Range...
Program End
According to above example we need to raise an
exception if user input number out of 1 to 10 range.
So we use raise keyword which helps to arise an
Exception when condition returns false otherwise it returns an output.
Processing exception in Python is the process of
handling errors that may occur during the execution of a Python
program. When an exception occurs, the Python interpreter will stop
execution of the program and raise an exception object.
The exception object contains information about the
type of exception, the location where the exception occurred, and any other
relevant data.
There are two main ways to handle exceptions in
Python:
1. using try/except statements and
2. using the built-in except function.
Try/except statements allow us to specify a block
of code that should be executed if an exception occurs. If an exception
occurs while the code in the try block is executing,
the except block will be executed instead.
The except function allows us to handle
exceptions globally. If an exception occurs, the except function
will be called.
Heres a detailed explanation of how exception
handling works in Python:
1.
Exception Types:
Python has a wide range of built-in exception types
to represent different types of errors. Common exceptions include TypeError,
ValueError, FileNotFoundError, IndexError, and ZeroDivisionError, among others.
You can also create custom exception classes by subclassing the built-in
Exception class to represent application-specific errors.
2.
The try Block:
You enclose the code that may raise an exception
within a try block.
If an
exception occurs within this block, Python stops executing the current code and
jumps to the corresponding except block.
3.
The except Block:
In the except block, you specify the type of
exception you want to catch.
You can catch specific exceptions or more general
exceptions. Catching specific exceptions allows you to handle different types
of errors differently.
You can use the as keyword to assign the exception
to a variable, making it accessible for further processing.
You can have multiple except blocks to catch
different types of exceptions.
Following is a syntax:
try:
# Code that may raise an exception
except SpecificException as e:
#
Handle the specific exception
except
AnotherException as e:
#
Handle another specific exception
except
Exception as e:
#
Catch more general exceptions
4. The
else Block:
The else block is executed if no exceptions were
raised in the try block.
You can use this block to specify code that should
run when the try block executes without errors.
Following is a syntax:
try:
# Code
that may raise an exception
except
Exception as e:
#
Handle the exception
else:
# Code
that runs when no exceptions occurred
5. The
finally Block:
The finally block is always executed, regardless of
whether an exception occurred or not.
Its typically used for cleanup tasks, like closing
files, network connections, or releasing resources.
Following is a syntax:
try:
# Code
that may raise an exception
except Exception as e:
#
Handle the exception
finally:
#
Cleanup code that always runs
6.
Raising Exceptions:
You can manually raise exceptions using the raise
statement. This is useful for indicating errors or exceptional conditions in
your code.
You can raise built-in exceptions or custom
exceptions that you define by creating new exception classes.
Following is a syntax:
if condition:
raise
ValueError("An error occurred.")
As we mentioned, exceptions are just regular
classes that inherit from the Exception class. This makes it super easy to
create our own custom exceptions, which can make our programs easier to follow
and more readable.
In Python, custom exceptions, also known as
user-defined exceptions, allow you to create your own exception classes to
handle specific error conditions in your code.
Custom exceptions in Python are exceptions that are
created by the programmer. They are used to handle specific errors that
are not covered by the built-in exceptions.
Custom exceptions can be created by deriving from
the Exception class.
Custom exception handling in Python involves
creating, raising, and handling custom exceptions.
Heres a step-by-step explanation of how to create
and use custom exceptions:
1.
Define a Custom Exception Class:
Create a custom exception class by defining a new
class that inherits from a built-in exception class, typically Exception.
Give your custom exception class a name that
reflects the type of error you want to handle.
Example:
class
CustomError(Exception):
def
__init__(self):
print(“A custom error occurred”)
In this example, CustomError is the custom
exception class that inherits from Exception. It includes an __init__ method to
set the error message.
2.
Raise the Custom Exception:
In your code, when a specific error condition
occurs, raise your custom exception using the raise statement.
Example:
a = -1
if a < 0:
raise CustomError("Value cannot be negative")
Output:
1 a = -1
2 if a
< 0:
----> 3
raise CustomError("Value cannot be negative")
Exception: Value cannot be negative
In this above example, raises the CustomError when
the input a is negative. It terminates the program to handle this this custom
error we have to use try and except block.
3.
Handle the Custom Exception:
To handle your custom exception, use a try and
except block. Catch the specific exception type you raised (in this case,
CustomError) and provide appropriate error-handling logic.
Example:
a = -1
try:
if
a < 0:
raise
CustomError
else:
print(“Your Number = ”,a)
except
CustomError:
print(“Cant Allow Negative Number”)
Output:
Cant Allow Negative Number
According to above example The except block catches
the CustomError and allows you to access the error message and perform actions
based on the error condition.
Thank You
:: Any Query::
Contact: Ruparel Education Pvt. Ltd.
Mobile No: 7600044051