0% found this document useful (0 votes)
5 views29 pages

Python Unit V

This document covers file handling in Python, including creating, reading, and writing text and binary files, as well as working with CSV and JSON formats. It also discusses exception handling, data visualization techniques using Matplotlib, and provides examples of reading and writing data in various formats. Additionally, it includes a section on computing polynomial equations using Python.

Uploaded by

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

Python Unit V

This document covers file handling in Python, including creating, reading, and writing text and binary files, as well as working with CSV and JSON formats. It also discusses exception handling, data visualization techniques using Matplotlib, and provides examples of reading and writing data in various formats. Additionally, it includes a section on computing polynomial equations using Python.

Uploaded by

rmeshak2007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT V:

Files: Types of Files; Creating, Reading and writing on Text and Binary Files;The Pickle
Module, Reading and Writing CSV Files. Reading and writing of csv and JSON files. Exception
Handling: Try-except-else-finally block, raise statement, hierarchy of exceptions, adding
exceptions. Data visualization: Plotting various 2D and 3D graphics; Histogram; Pi charts; Sine
and cosine curves.

File Handling in Python


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.

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

r Read mode. Opens a file for reading. The file must exist.

Write mode. Opens a file for writing. Creates a new file if it doesn’t exist or truncates
w the file if it exists.

a Append mode. Opens a file for appending. Creates a new file if it doesn’t exist.

b Binary mode. Opens a file in binary mode.

t Text mode. Opens a file in text mode. Default mode.

x Exclusive creation mode. Creates a new file and fails if it already exists.

r+ Read and write mode. Opens a file for both reading and writing. The file must exist.

Write and read mode. Opens a file for both writing and reading. Creates a new file if it
w+ doesn’t exist or truncates the file if it exists.

Append and read mode. Opens a file for appending and reading. Creates a new file if it
a+ doesn’t exist.

1
Opening a File in Python
To open a file we can use open() function, which requires file path and mode as arguments:
Table of Content
OPEN A FILE
 Reading a File
 Writing to a File
 append to a file
 Closing a File
 Handling Exceptions When Closing a File

Reading a File
Reading a file can be achieved by [Link]() which reads the entire content of the file. After
reading the file we can close the file using [Link]() which closes the file after reading it,
which is necessary to free up system resources.

Example:
[Link]
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()

[Link]
Hello world
GeeksforGeeks
123 456

Output:
Hello world
GeeksforGeeks
123 456

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many
characters you want to return:

Example

Return the 5 first characters of the file:

f = open("[Link]", "r")
print([Link](5))

2
[Link]
Hello world
GeeksforGeeks
123 456
Output:

Hello

Read Lines

You can return one line by using the readline() method:

Example

Read one line of the file:

f = open("[Link]", "r")
print([Link]())

output:

Hello world

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:

f = open("[Link]", "r")
print([Link]())
print([Link]())

output:

Hello world
GeeksforGeeks

By looping through the lines of the file, you can read the whole file, line by line:

Example

Loop through the file line by line:

3
f = open("[Link]", "r")
for x in f:
print(x)

OUPUT:

Hello world
GeeksforGeeks
123 456

Writing to a File
Writing to a file is done using [Link]() which writes the specified string to the file. If the file
exists, its content is erased. If it doesn’t exist, a new file is created.

file = open("[Link]", "w")


[Link]("Hello, World!")
[Link]()

[Link]
I like python
Output:
[Link]
Hello, World!

Writing to a File in Append Mode (a)


It is done using [Link]() which adds the specified string to the end of the file without erasing
its existing content.
# Python code to illustrate append() mode
file = open('[Link]', 'a')
[Link]("This will add this line")
[Link]()
Output:
[Link]
Hello, World!
This will add this line

4
Reading a File in Binary Mode (rb)
file = open("[Link]", "rb")
content = [Link]()
print(content)
[Link]()

Output:
b'Hello world\r\nGeeksforGeeks\r\n123 456'

Reading a File in TEXT Mode (rb)


file = open("[Link]", "rt")
content = [Link]()
print(content)
[Link]()

Output:

Closing a File
Closing a file is essential to ensure that all resources used by the file are properly
released. [Link]() method closes the file and ensures that any changes made to the file are
saved.
file = open("[Link]", "r")
# Perform file operations
[Link]()

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.

with open("[Link]", "r") as file:


content = [Link]()
print(content)

5
Handling Exceptions When Closing a File
It’s important to handle exceptions to ensure that files are closed properly, even if an error
occurs during file operations.

try:
file = open("[Link]", "r")
content = [Link]()
print(content)
finally:
print(“welcome to file”)
[Link]()

Python CSV: Read and Write CSV Files

The CSV (Comma Separated Values) format is a common and straightforward way to store
tabular data. To represent a CSV file, it should have the .csv file extension.
Now, let's proceed with an example of the info .csv file and its data.

SN, Name, City


1, Michael, New Jersey
2, Jack, California

Working With CSV Files in Python

Python provides a dedicated csv module to work with csv files. The module includes various
methods to perform different operations.
However, we first need to import the module using:

import csv

6
Read CSV Files with Python

The csv module provides the [Link]() function to read a CSV file.
Suppose we have a csv file named [Link] with the following entries.

Name, Age, Profession


Jack, 23, Doctor
Miller, 22, Engineer

Now, let's read this csv file.

import csv

with open('[Link]', 'r') as file:


reader = [Link](file)

for row in reader:


print(row)

Output

['Name', 'Age', 'Profession']


['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']

Here, we have opened the [Link] file in reading mode using:

with open([Link]', 'r') as file:

We then used the [Link]() function to read the file. To learn more about reading csv
files, Python Reading CSV Files.
[Link]()for More Readable Code

Write to CSV Files with Python

The csv module provides the [Link]() function to write to a CSV file.
Let's look at an example.

import csv

7
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](["SN", "Movie", "Protagonist"])
[Link]([1, "Lord of the Rings", "Frodo Baggins"])
[Link]([2, "Harry Potter", "Harry Potter"])

When we run the above program, a [Link] file is created with the following content:

SN,Movie,Protagonist
1,Lord of the Rings,Frodo Baggins
2,Harry Potter,Harry Potter

In this example, we have created the CSV file named [Link] in the writing mode.
We then used the [Link]() function to write to the file. To learn more about writing to a csv
file, Python Writing CSV Files.
Here,

 [Link](["SN", "Movie", "Protagonist"]) writes the header row with column names to
the CSV file.
 [Link]([1, "Lord of the Rings", "Frodo Baggins"]) writes the first data row to the CSV
file.
 [Link]([2, "Harry Potter", "Harry Potter"]) writes the second data row to the CSV file.
Writing Dictionaries to CSV Files

Using Python Pandas to Handle CSV Files

Pandas is a popular data science library in Python for data manipulation and analysis.
If we are working with huge chunks of data, it's better to use pandas to handle CSV files for ease
and efficiency.

Read CSV Files

To read the CSV file using pandas, we can use the read_csv() function.

import pandas as pd
pd.read_csv("[Link]")

Here, the program reads [Link] from the current directory.

8
Write to a CSV Files

To write to a CSV file, we need to use the to_csv() function of a DataFrame.

import pandas as pd

# creating a data frame


df = [Link]([['Jack', 24], ['Rose', 22]], columns = ['Name', 'Age'])

# writing data frame to a CSV file


df.to_csv('[Link]')

Here, we have created a DataFrame using the [Link]() method. Then,


the to_csv() function for this object is called, to write into [Link].

Name age
Jack 24
Rose 22

Reading CSV Files

Python's built-in csv module makes it easy to read and write CSV files. To read a CSV file, you
can use the [Link] function.

Example:

In this example:

 open('[Link]', mode='r') opens the CSV file in read mode.

9
[Link](file) reads the file as a CSV.
The for row in csv_reader loop iterates over each row in the CSV file.
Writing to CSV Files

To write data to a CSV file, you can use the [Link] function.

Example:

In this example:

 open('[Link]', mode='w', newline='') opens the file in write mode.


 [Link](file) creates a CSV writer object.
 csv_writer.writerows(data) writes multiple rows to the CSV file.
Using DictReader and DictWriter
The DictReader and DictWriter classes allow you to read and write CSV files using dictionaries.

10
Working with JSON Files

JSON stands for JavaScript Object Notation. It's a text-based format for storing and exchanging
data that's readable by both humans and machines. JSON is often used in web development, data
analysis, and software engineering.

What is JSON (JavaScript Object Notation)?

JSON (JavaScript Object Notation) is a text-based, human-readable data interchange format used
to exchange data between web clients and web servers. The format defines a set of structuring
rules for the representation of structured data. JSON is used as an alternative to Extensible
Markup Language (XML).

Reading JSON Files

Python’s built-in json module allows you to read and write JSON files easily. To read a JSON
file, you can use the [Link] function.

[Link]

{
"Subjects": {

11
"Maths":85,
"Physics":90
}
}

Example:

In this example:

 open ('[Link]', mode='r') opens the JSON file in read mode.


 [Link](file) reads the file and parses the JSON data.
Writing to JSON Files
To write data to a JSON file, you can use the [Link] function.

Example:

12
In this example:

 open ('[Link]', mode='w') opens the file in write mode.


 [Link](data, file, indent=4) writes the dictionary data to the file in JSON format with an
indentation of 4 spaces.
Matplotlib:

We'll start by importing matplotlib and numpy using the standard lines import [Link]
as plt and import numpy as np. This means we can use the short alias plt and np when we call
these two libraries. You could import numpy as wonderburger and use [Link]() to call
the numpy sine function, but this would look funny to other engineers. The line import numpy as
np has become a common convention and will look familiar to other engineers using Python. In
case you are working in a Juypiter notebook, the %matplotlib inline command is also necessary
to view the plots directly in the notebook.

In [1]:
import [Link] as plt
import numpy as np
# if using a jupyter notebook
%matplotlib inline

Next we will build a set of x values from zero to 4π in increments of 0.1 radians to use in our
plot.

13
The x-values are stored in a numpy array. Numpy's arange() function has three
arguments: start, stop, step. We start at zero, stop at 4π and step by 0.1 radians. Then we
define a variable y as the sine of x using numpy's sin() function.

In [2]:
x = [Link](0,4*[Link],0.1) # start,stop,step
y = [Link](x)

To create the plot, we use matplotlib's [Link]() function. The two arguments are our numpy
arrays x and y. The line [Link]() will show the finished plot.

In [3]:
[Link](x,y)
[Link]()

Next let's build a plot which shows two trig functions, sine and cosine. We will create the same
two numpy arrays x and y as before, and add a third numpy array z which is the cosine of x.

In [4]:
x = [Link](0,4*[Link],0.1) # start,stop,step
y = [Link](x)
z = [Link](x)

To plot both sine and cosine on the same set of axies, we need to include two pair of x,y values
in our [Link]() arguments. The first pair is x,y. This corresponds to the sine function. The
second pair is x,z. This correspons to the cosine function. If you try and only add three
arguments as in [Link](x,y,z), your plot will not show sine and cosine on the same set of axes.

In [5]:
[Link](x,y,x,z)
[Link]()

Let's build one more plot, a plot which shows the sine and cosine of x and also includes axis
labels, a title and a legend. We build the numpy arrays using the trig functions as before:

In [6]:
x = [Link](0,4*[Link]-1,0.1) # start,stop,step
y = [Link](x)

14
z = [Link](x)

The [Link]() call is the same as before using two pairs of x and y values. To add axis labels we
will use the following methods:

matplotlib method description example

[Link]() x-axis label [Link]('x values from 0 to 4pi')

[Link]() y-axis label [Link]('sin(x) and cos(x)')

[Link]() plot title [Link]('Plot of sin and cos from 0 to 4pi')

[Link]([ ]) legend [Link](['sin(x)', 'cos(x)'])

Note that [Link]() method requires a list of strings (['string1', 'string2']), where the individual
strings are enclosed with qutoes, then seperated by commas and finally inclosed in brackets to
make a list. The first string in the list corresponds to the first x-y pair when we called [Link]() ,
the second string in the list corresponds to the second x,y pair in the [Link]() line.

In [7]:
[Link](x,y,x,z)
[Link]('x values from 0 to 4pi') # string must be enclosed with quotes ' '
[Link]('sin(x) and cos(x)')
[Link]('Plot of sin and cos from 0 to 4pi')
[Link](['sin(x)', 'cos(x)']) # legend entries as seperate strings in a list
[Link]()

15
Python program to Compute a Polynomial Equation


The following article contains programs to compute a polynomial equation given that the
coefficients of the polynomial are stored in a List.
Examples:
# Evaluate value of 2x3 - 6x2 + 2x - 1 for x = 3
Input: poly[] = {2, -6, 2, -1}, x = 3
Output: 5

# Evaluate value of 2x3 + 3x + 1 for x = 2


Input: poly[] = {2, 0, 3, 1}, x = 2
Output: 23

# Evaluate value of 2x + 5 for x = 5


Input: poly[] = {2, 5}, x = 5
Output: 15

Example

Import numpy and matplotlib then draw the line of Polynomial Regression:

import numpy
import [Link] as plt

x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]

mymodel = numpy.poly1d([Link](x, y, 3))

myline = [Link](1, 22, 100)

[Link](x, y)
[Link](myline, mymodel(myline))
[Link]()

16
Result:

Example Explained

Import the modules you need.

You can learn about the NumPy module in our NumPy Tutorial.

You can learn about the SciPy module in our SciPy Tutorial.

import numpy
import [Link] as plt

Create the arrays that represent the values of the x and y axis:

x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]

NumPy has a method that lets us make a polynomial model:

17
mymodel = numpy.poly1d([Link](x, y, 3))

Then specify how the line will display, we start at position 1, and end at position 22:

myline = [Link](1, 22, 100)

Draw the original scatter plot:

[Link](x, y)

Draw the line of polynomial regression:

[Link](myline, mymodel(myline))

Display the diagram:

[Link]()

Exponential curve fitting

We will be repeating the same process as above, but the only difference is the logarithmic
function is replaced by the exponential function.

First, let us create the data points

x_data = [Link]([11, 19, 31, 39, 51])


print(x_data)

y_data = [Link]([5, 8, 32, 84, 110])


print(y_data)

Output:

Equation: y = e(ax)*e(b)

18
In this equation we will plot the graph and the a, b are coefficients which we can be obtained
with [Link]() method. Now lets us find the coefficients of exponential function with
degree .

 Python3

ylog_data = [Link](y_data)
print(ylog_data)

curve_fit = [Link](x_data, log_y_data, 1)


print(curve_fit)

Output:

So, a = 0.69 and b = 0.085 these are the coefficients we can get the equation of the curve
which would be (y = e (ax)*e(b), where a, b are coefficient)
y = e(0.69x)*e(0.085) final equation.

 Python3

y = [Link](0.69) * [Link](0.085*x_data)

print(y)

Output:

Now, let us plot the graphs with the help of [Link]() function.

 Python3

# Blue
[Link](x_data, y_data)

# best fit in orange

19
[Link](x_data, y)

Output:

In the above graph blue line represents the graph of original x and y coordinates and the
orange line is the graph of coordinates that we have obtained through our calculations, and it
is the best fit.

Hence, this is the process of fitting exponential and logarithmic curves in Python with the
help of NumPy and matplotlib.

20
What Is a Bar Graph?

A bar graph is a chart that plots data using rectangular bars or columns (called bins) that represent
the total amount of observations in the data for that category. Bar charts can be displayed with
vertical columns, horizontal bars, comparative bars (multiple bars to show a comparison between
values), or stacked bars (bars containing multiple types of information).

What Is a CSV File?

A CSV File (comma-separated values) is a text file that stores data in the form of columns,
separated by commas, and rows are distinguished by line breaks.

Comma separated value file means that the data is actually input as data that is separated by
commas. The spreadsheet application converts those comma-separated pieces of data into cells in
tables and columns to make it easier to read and edit.

Now let’s start creating bar graph.

1. First we have to Import necessary modules


import [Link] as plt
import pandas as pd

2. Next we have to read the csv file data.


data = pd.read_csv('[Link]')

here we are using a csv file named ‘[Link]’.

21
innovative companies list

3. Create DataFrame
df = [Link](data)

4. Initialize the lists for X and Y


X = list([Link][:, 0])
Y = list([Link][:, 1])

.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used
with a boolean array.

5. Plot bar graph


# Plot the data using bar()
[Link](X, Y, color='g')
[Link]("innovative companies")
[Link]("Countries")
[Link]("Number of Companies")

6. Display graph
# Show the [Link]()

22
Exception Handling: Try-except-else-finally block, raise statement, hierarchy of exceptions,
adding exceptions.

Exception:

An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is
called an exception.

Exception Handling:

Python Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running program. It
enables you to catch and manage errors, making your code more robust and user-friendly.

Exceptions abnormally terminate the execution of a program, it is important to handle


exceptions. In Python, we use the try...except block to handle exceptions.

Python try...except Block

The try...except block is used to handle exceptions in Python. Here's the syntax
of try...except block:

try:
# code that may cause exception
except:
# code to run when exception occurs

we have placed the code that might generate an exception inside the try block. Every try block is
followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.

Example:

23
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0.

Python try with else clause

we might want to run a certain block of code if the code block inside try runs without any errors.
For these cases, you can use the optional else keyword with the try statement.

try:
num = int(input("Enter a number: "))
if num % 2 == 0
except:
print("Not an even number!")
else:
print(“number is even”)

Output:

Enter a number:5

Not an even number

Enter a number:6

Number is even

Python try...finally

In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.

24
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

finally:
print("This is finally block.")

Output

Error: Denominator cannot be 0.


This is finally block.

Python Raise an Exception

The raise statement in Python is used to raise an exception. Try-except blocks can be used to
manage exceptions, which are errors that happen while a programme is running. When an
exception is triggered, the programme goes to the closest exception handler, interrupting the
regular flow of execution.

o The raise keyword is typically used inside a function or method, and is used to indicate
an error condition.
o We can throw an exception and immediately halt the running of your programme by
using the raise keyword.
o Python looks for the closest exception handler, which is often defined using a try-except
block, when an exception is triggered.
o If an exception handler is discovered, its code is performed, and the try-except block's
starting point is reached again.
o If an exception handler cannot be located, the software crashes and an error message
appears.

def divide(a, b):


if b == 0:
raise Exception(" Cannot divide by zero. ")
return a / b

25
try:
result = divide(10, 0)
except Exception as e:
print(" An error occurred: ", e)

Output:
An error occurred: Age must be 18 or above.

The Python Exception Class Hierarchy

The Python exception class hierarchy consists of a few different exceptions spread across a
handful of important base class types. As with most programming languages, errors occur
within a Python application when something unexpected goes wrong. Anything from
improper arithmetic and running out of memory to invalid file references and unicode
formatting errors may be raised by Python under certain circumstances.

BaseException

Exception

o ArithmeticError
 FloatingPointError
 OverflowError
 ZeroDivisionError

Matplotlib Histograms
Histogram

A histogram is representation of a continuous data.

It represents numerical data.

A histogram is a graph showing frequency distributions.

It s a graph showing the number of observations within each given interval.

Create Histogram

In Matplotlib, we use the hist() function to create histograms.

26
The hist() function will use an array of numbers to create a histogram, the array is sent into
the function as an argument.

We can use a histogram plot when the data remains distributed, whereas we can use a bar
graph to compare two entities. Both histogram and bar plot look alike but are used in
different scenarios. In Matplotlib, the hist() function represents this.

Example:

import [Link] as plt


import numpy as np

marks= [Link]([74,45,65,25,72,44,55,35,61])
bins = [0,20,40,60,80,100]
[Link](marks, bins)
[Link](''marks”)
[Link]('Number of people')
[Link]('Histogram')

# Print the chart


[Link]()
Program Output:

27
Data Visualization 2D &3D Graphics:

Data visualization is a specialized vertical of data science where many libraries were
developed using Python. Among these, Matplotlib got the most popular choice for rendering
data visualizations to get a better insight. Initially, Matplotlib was used to create 2D
plotting charts like line charts, bar charts, histograms, scatter plots, pie plots, etc.
Matplotlib creators decided to extend its capabilities to deliver 3D plotting modules also.
Three-dimensional plots can be used by importing the mplot3d toolkit; It comes pre-installed
with Matplotlib installation:

Syntax:

from mpl_toolkits import mplot3d


Generate a Blank 3D Plot
An empty 3D plot can be created by passing the keyword projection='3D' to the axis creation
function:

Example:

import [Link] as pyplot


import numpy as np
from mpl_toolkits import mplot3d

fig = [Link](figsize = (6, 6))


ax = [Link](projection = '3d')

# Print the chart


[Link]()

28
29

You might also like