Search This Blog

Saturday, 18 December 2021

Program to read each row from a given CSV file

Example 1 : Write a Python program to read each row from a given csv file and print a list of strings.
Note : delimiter: A one-character string used to separate fields. It defaults to ','.

quotechar: The quotechar optional parameter tells the writer which character to use to quote fields when writing.

Python code
	
import csv
with open('departments.csv', newline='') as csvfile:
 data = csv.reader(csvfile, delimiter=' ', quotechar='|')
 for row in data:
   print(', '.join(row))	
	
departments.csv
	
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
100,Finance,108,1700
110,Accounting,205,1700
120,Treasury,,1700
130,Corporate Tax,,1700
140,Control And Credit,,1700
150,Shareholder Services,,1700
160,Benefits,,1700
170,Manufacturing,,1700
180,Construction,,1700
190,Contracting,,1700
200,Operations,,1700
210,IT Support,,1700
220,NOC,,1700
230,IT Helpdesk,,1700
240,Government Sales,,1700
250,Retail Sales,,1700
260,Recruiting,,1700
270,Payroll,,1700
	
Output:
	
department_id,department_name,manager_id,location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human, Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
70,Public, Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
100,Finance,108,1700
110,Accounting,205,1700
120,Treasury,,1700
130,Corporate, Tax,,1700
140,Control, And, Credit,,1700
150,Shareholder, Services,,1700
160,Benefits,,1700
170,Manufacturing,,1700
180,Construction,,1700
190,Contracting,,1700
200,Operations,,1700
210,IT, Support,,1700
220,NOC,,1700
230,IT, Helpdesk,,1700
240,Government, Sales,,1700
250,Retail, Sales,,1700
260,Recruiting,,1700
270,Payroll,,1700	
	

Pickling (Pickle Library) Python

What is Pickling:

Python pickle module is used for serializing and de-serializing python object structures. The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s and 1s) is called pickling or serialization or flattening or marshalling. We can converts the byte stream (generated through pickling) back into python objects by a process called as unpickling. 


Pickle examples:

Below is a simple program on how to pickle a list:


Pickle a simple list: Pickle_list1.py

import pickle
mylist = ['a', 'b', 'c', 'd']
with open('datafile.txt', 'wb') as fh:
   pickle.dump(mylist, fh)

In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’). We open the file in “wb” mode instead of “w” as all the operations are done using bytes in the current working directory. A new file named “datafile.txt” is created, which converts the mylist data in the byte stream.


Unpickle a simple list: unpickle_list1.py

import pickle
pickle_off = open ("datafile.txt", "rb")
emp = pickle.load(pickle_off)
print(emp)

Output: On running above scripts, you can see your mylist data again as output.

['a', 'b', 'c', 'd']

Pickle a simple dictionary −

import pickle
EmpID = {1:"Zack",2:"53050",3:"IT",4:"38",5:"Flipkart"}
pickling_on = open("EmpID.pickle","wb")
pickle.dump(EmpID, pickling_on)
pickling_on.close()

Unpickle a dictionary −

import pickle
pickle_off = open("EmpID.pickle", 'rb')
EmpID = pickle.load(pickle_off)
print(EmpID)

On running above script(unpickle) we get our dictionary back as we initialized earlier. Also, please note because we are reading bytes here, we have used “rb” instead of “r”.

Output

{1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'}

Pickle Exceptions


Below are some of the common exceptions raised while dealing with pickle module −

  • Pickle.PicklingError: If the pickle object doesn’t support pickling, this exception is raised.
  • Pickle.UnpicklingError: In case the file contains bad or corrupted data.
  • EOFError: In case the end of file is detected, this exception is raised.

Prons:

  • Comes handy to save complicated data.
  • Easy to use, lighter and doesn’t require several lines of code.
  • The pickled file generated is not easily readable and thus provide some security.

Cons:

  • Languages other than python may not able to reconstruct pickled python objects.
  • Risk of unpickling data from malicious sources.

Wednesday, 15 December 2021

Inheritance in Python

Python Inheritance

how to make your own site

Instead of starting from a scratch, you can create a class by deriving it from a pre-existing class by listing the parent class in parentheses after the new class name.


The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax :

class SubClassName (ParentClass1[, ParentClass2, ...]):
    'Optional class documentation string'
    class_suite

example :

class Parent: # define parent class
    parentAttr = 100

    def __init__(self):
       print ("Calling parent constructor")

    def parentMethod(self):
       print ('Calling parent method')

    def setAttr(self, attr):
       Parent.parentAttr = attr

    def getAttr(self):
       print ("Parent attribute :", Parent.parentAttr)

 class Child(Parent): # define child class
    def __init__(self):
       print ("Calling child constructor")

    def childMethod(self):
       print ('Calling child method')

c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

output of above example  :

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

In a similar way, you can drive a class from multiple parent classes. multiple inheritance we will learn in next tutorial.

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

  • issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the superclass sup. 
  • isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an instance of a subclass of Class 

Overriding Methods

You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.

Example :

class Parent: # define parent class
   def myMethod(self):
      print ('Calling parent method')


class Child(Parent): # define child class
   def myMethod(self):
      print ('Calling child method')


c = Child() # instance of child
c.myMethod() # child calls overridden method

output of above example  :

Calling child method

Base Overloading Methods

The following table lists some generic functionality that you can override in your own classes −

MethodDescription 
__init__ ( self [,args...] )Constructor (with any optional arguments)

Sample Call : obj = className(args)
__del__( self )Destructor, deletes an object

Sample Call : del obj
__repr__( self )Evaluatable string representation

Sample Call : repr(obj)
 

__str__( self )
Printable string representation

Sample Call : str(obj)
__cmp__ ( self, x )Object comparison

Sample Call : cmp(obj, x)

Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.


You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation

Example :

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

output of above example  :

Vector(7,8)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then will not be directly visible to outsiders.

Example :

class JustCounter:
   __secretCount = 0

   def count(self):
      self.__secretCount += 1
      print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)

output of above example  :

1
2
Traceback (most recent call last):
   File "test.py", line 12, in
      print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −

.........................
print (counter._JustCounter__secretCount)

output of above example  :

1
2
2

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...