Python Unit V
Python 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.
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.
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
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
f = open("[Link]", "r")
print([Link](5))
2
[Link]
Hello world
GeeksforGeeks
123 456
Output:
Hello
Read Lines
Example
f = open("[Link]", "r")
print([Link]())
output:
Hello world
By calling readline() two times, you can read the two first lines:
Example
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
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.
[Link]
I like python
Output:
[Link]
Hello, World!
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'
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]()
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]()
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.
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.
import csv
Output
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
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
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.
To read the CSV file using pandas, we can use the read_csv() function.
import pandas as pd
pd.read_csv("[Link]")
8
Write to a CSV Files
import pandas as pd
Name age
Jack 24
Rose 22
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:
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:
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.
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).
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:
Example:
12
In this example:
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:
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
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]
[Link](x, y)
[Link](myline, mymodel(myline))
[Link]()
16
Result:
Example Explained
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]
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:
[Link](x, y)
[Link](myline, mymodel(myline))
[Link]()
We will be repeating the same process as above, but the only difference is the logarithmic
function is replaced by the exponential function.
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)
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)
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).
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.
21
innovative companies list
3. Create DataFrame
df = [Link](data)
.iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used
with a boolean array.
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.
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.")
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
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
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.
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 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
Create Histogram
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:
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')
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:
Example:
28
29