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

Unit - V

Uploaded by

Chanakya Varma
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)
13 views29 pages

Unit - V

Uploaded by

Chanakya Varma
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/ 29

UNIT -V

Python File I/O


• Files are named locations on disk to store related information.
• They are used to permanently store data in a non-volatile
memory (e.g. hard disk).
• When we want to read from or write to a file, we need to open it
first. When we are done, it needs to be closed so that the
resources that are tied with the file are freed.
• Hence, in Python, a file operation takes place in the following
order:
1.Open a file
2.Read or write (perform operation)
3.Close the file
• Opening Files in Python
• Python has a built-in open() function to open a file.
• This function returns a file object, also called a handle.
• it is used to read or modify the file accordingly.
• Example:
• f = open("test.txt") # open file in current directory
• f = open("C:/Python38/README.txt") # specifying full path
• We can specify the mode while opening a file.
• In mode, we specify whether we want to read r, write w or append a to
the file.
• We can also specify if we want to open the file in text mode or binary
mode.
• The default is reading in text mode.
• In this mode, we get strings when reading from the file.
• On the other hand, binary mode returns bytes and this is the mode to
be used when dealing with non-text files like images or executable
files.
• f = open("test.txt") # equivalent to 'r' or 'rt'
• f = open("test.txt",'w') # write in text mode
• f = open("img.bmp",'r+b') # read and write in binary mode
• Closing Files in Python
• When we are done with performing operations on the file, we need to
properly close the file.
• Closing a file will free up the resources that were tied with the file.
• It is done using the close() method available in Python.
• Python has a garbage collector to clean up unreferenced objects but we
must not rely on it to close the file.
• Example:
• f = open("test.txt")
• f.close()
• Writing to Files in Python
• In order to write into a file in Python, we need to open it in write w, append
a or exclusive creation x mode.
• We need to be careful with the w mode, as it will overwrite into the file if it
already exists.
• Due to this, all the previous data are erased.
• Writing a string or sequence of bytes (for binary files) is done using the
write() method.
• This method returns the number of characters written to the file.
• Example:
• with open("test.txt",'w',encoding = 'utf-8') as f:
• f.write("my first file\n")
• f.write("This file\n\n")
• f.write("contains three lines\n")
• Reading Files in Python
• To read a file in Python, we must open the file in reading r mode.
• There are various methods available for this purpose. We can use the read(size)
method to read in the size number of data. If the size parameter is not
specified, it reads and returns up to the end of the file.
• We can read the text.txt file we wrote in the above section in the following
way:
• f = open("test.txt",'r',encoding = 'utf-8')
• f.read(4) # read the first 4 data
• 'This'
• f.read(4) # read the next 4 data
• ' is '
• f.read() # read in the rest till end of file
• 'my first file\nThis file\ncontains three lines\n'
• f.read() # further reading returns empty sting
• We can change our current file cursor (position) using the seek() method.
• Similarly, the tell() method returns our current position (in number of bytes).
• >>> f.tell() # get the current file position
• 56
• >>> f.seek(0) # bring file cursor to initial position
• 0
• >>> print(f.read()) # read the entire file
• This is my first file
• This file
• contains three lines
• Format operator (%)
• The format operator, % allows us to construct strings, replacing parts
of the strings with the data stored in variables. When applied to
integers, % is the modulus operator.
• But when the first operand is a string, % is the format operator.
• sno= 42
• print('My Regd. No: %d is even number.' % sno)
• #output: My Regd. No: 42 is even number.
Command Line Arguments
• The arguments that are given after the name of the program in the
command line shell of the operating system are known as Command
Line Arguments.
• Python provides various ways of dealing with these types of
arguments.
• Using sys.argv
Using sys.argv to access Command Line Args
• The sys module provides functions and variables to manipulate different parts of the
Python runtime environment.
• Example:
• import sys
• n = len(sys.argv) # total arguments
• print("Total arguments passed:", n)
• # Arguments passed
• print("\nName of Python script:", sys.argv[0])
• print("\nArguments passed:", end = " ")
• for i in range(1, n):
• print(sys.argv[i], end = " ")
Numpy
• NumPy stands for Numeric Python
• It is a python package for the computation and processing of the
multidimensional and single dimensional array elements.
• NumPy is an open source library.
• It is a very useful library to perform mathematical and statistical
operations in Python.
• It has been built to work with the N-dimensional array, linear algebra,
random number, Fourier transform, etc.
• deals with multi-dimensional arrays and matrices
There are the following advantages or uses
of NumPy:
• It is used for Data Analysis
• It performs array-oriented computing.
• It efficiently implements the multidimensional arrays.
• It performs scientific computations.
• It is capable of performing Fourier Transform and reshaping the data
stored in multidimensional arrays.
• NumPy provides the in-built functions for linear algebra and random
number generation.
• NumPy doesn't come bundled with Python.
• We have to install it using the python pip installer.
• Execute the following command.
• pip install numpy
Creating a NumPy Array
• a= [1,9,8,3] # python list
• To convert python list to a numpy array by using the object np.array
• arr = np.array(a)
• print(arr) # array([1, 9, 8, 3])
• direct method is:
• a = np.array([1,9,8,3])
• print(a) # array([1,9,8,3])
• arr = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 23]])
• output:
• [
• [1, 2, 3, 4]
• [4, 5, 6, 7]
• [9, 10, 11, 23]
• ]
numpy.reshape() function in Python
• Python NumPy Reshape function is used to shape an array without changing
its data.
• In some occasions, you may need to reshape the data from wide to long.
• You can use the np.reshape function for this.
• Syntax of np.reshape()
• numpy.reshape(a, newShape, order='C')
• Here,
• a: Array that you want to reshape
• newShape: The new desires shape
• Order: Default is C which is an essential row style.
Reshaping arrays
• Reshaping means changing the shape of an array.
• The shape of an array is the number of elements in each dimension.
• By reshaping we can add or remove dimensions or change number of
elements in each dimension.
• Example: Reshape From 1-D to 2-D
• import numpy as np
• arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
• newarr = arr.reshape(4, 3)
• print(newarr)
• Example:
• import numpy as np
• e = np.array([(1,2,3), (4,5,6)])
• print(e)
• e.reshape(3,2)

• // Before reshape
• [[1 2 3]
• [4 5 6]]

• //After Reshape
• array([[1, 2],
• [3, 4],
Numpy – min, max, sum, sort, search
• import numpy
• arr = numpy.array([1, 5, 4, 8, 3, 7]) # creating a numpy array of integers
• big= numpy.max(arr) # finding the maximum and
• small = numpy.min(arr) # minimum element in the array
• print(np.sum(arr)) # sum of array elements
• print(np.sort(arr)) # sort the elemnts
• You can search an array for a certain value, and return the indexes that get a match.
• To search an array, use the where() method.
• import numpy as np
• arr = np.array([1, 2, 3, 4, 5, 4, 4])
• x = np.where(arr == 4)
• print(x) # (array([3, 5, 6]),)
Matplot Lib
• Matplotlib is a low level graph plotting library in python that
serves as a visualization utility.
• It is open-source library.
• pip install matplotlib # Installing
• Once Matplotlib is installed, import it in your applications by
adding the import module statement:
• import matplotlib
• print(matplotlib.__version__) # checking the version
Purpose of Matplot library
• Matplotlib is a library for creating static, animated, and interactive
visualizations in Python.
• Matplotlib can be used for publication quality plots.
• it can be used for creating interactive figures that can zoom, pan,
update.
• Pyplot
• Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:
• import matplotlib.pyplot as plt
• Example: Draw a line in a diagram from position (0,0) to position
(6,250):
• import matplotlib.pyplot as plt
• import numpy as np
• x = np.array([0, 6])
• y = np.array([0, 250])
• plt.plot(x, y)
• plt.show()
• Plotting x and y points – using plot() function
• By default, plot() function draws a line from point to point.
• The function takes 2 parameters.
• Example:
• If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8]
and [3, 10] to the plot function.
• Code:
• import matplotlib.pyplot as plt
• import numpy as np
• x = np.array([1, 8])
• y = np.array([3, 10])
• plt.plot(x, y) # plt.plot(x,
y,'o')
• plt.show()
Multiple Points
• Example
• Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):

• import matplotlib.pyplot as plt


• import numpy as np

• xpoints = np.array([1, 2, 6, 8])


• ypoints = np.array([3, 8, 1, 10])

• plt.plot(xpoints, ypoints)
• plt.show()
• Example: Matplotlib Pie Charts - pie() function
• import matplotlib.pyplot as plt
• import numpy as np
• y = np.array([35, 25, 25, 15])
• mylabels = ["GITAM", "VIT", "KL Univ", "SRM"]
• plt.pie(y, labels = mylabels)
• plt.show()
• Creating Bars -bar() function
• import sys
• import matplotlib
• import matplotlib.pyplot as plt
• import numpy as np
• x = np.array(["VIT-AP", "GITAM", "AU", "IITM"])
• y = np.array([10, 8, 6, 9])
• plt.bar(x,y)
• plt.show()
Matplotlib Subplot
• it is used to display Multiple Plots
• provides a way to plot multiple plots on a single figure
• subplot() function you can draw multiple plots in one figure
• Example: Draw 2 plots:
• import matplotlib.pyplot as plt
• import numpy as np
• #plot 1:
• x = np.array([0, 1, 2, 3])
• y = np.array([3, 8, 1, 10])
• plt.subplot(1, 2, 1)
• plt.plot(x,y)
• #plot 2:
• x = np.array([0, 1, 2, 3])
• y = np.array([10, 20, 30, 40])
• plt.subplot(1, 2, 2)
• plt.plot(x,y)
• plt.show()
Package
• We usually organize our files in different folders and subfolders based on
some criteria, so that they can be managed easily and efficiently. For
example, we keep all our games in a Games folder and we can even
subcategorize according to the genre of the game or something like this.
The same analogy is followed by the Python package.
• A Python module may contain several classes, functions, variables, etc.
whereas a Python package can contains several module. In simpler terms a
package is folder that contains various modules as files.
• Creating Package
• Let’s create a package named mypckg that will contain two modules mod1
and mod2. To create this module follow the below steps –
• Create a folder named mypckg.
• Inside this folder create an empty Python file i.e. __init__.py
• Then create two modules mod1 and mod2 in this folder.

You might also like