Advertisement
182days

Class read and write to file (pickle)

May 5th, 2016
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #class to create shape instances, print details, write output to binary file, read output from binary file
  2. import pickle
  3. class Shape:
  4.  
  5.     def __init__(self, x, y, name):
  6.         self.x = x
  7.         self.y = y
  8.         self.name = name
  9.          
  10.     def area(self): #calculate area of new shape
  11.         return self.x * self.y
  12.  
  13.     def perimeter(self): #calculate perimeter of new shape
  14.         return 2 * self.x + 2 * self.y
  15.  
  16.     def scaleSize(self, scale): #function to scale new shape
  17.         self.x = self.x * scale
  18.         self.y = self.y * scale
  19.        
  20.     def printname(self): #prints name of a shape
  21.         return self.name
  22.  
  23. with open('shapes.dat', 'wb') as output: #opens binary file for writing to
  24.     rectangle = Shape(100,45,'rectangle')
  25.     pickle.dump(rectangle, output, pickle.HIGHEST_PROTOCOL) #dumps the output to the file
  26.  
  27.     square = Shape(55,15,'square')
  28.     pickle.dump(square, output, pickle.HIGHEST_PROTOCOL) #dumps the output to the file
  29.  
  30. with open('shapes.dat', 'rb') as input: #opens the binary file in read mode and prints requested content
  31.     rectangle = pickle.load(input)
  32.     print(rectangle.name)
  33.     print(rectangle.x)
  34.     print(rectangle.y)
  35.  
  36.     square = pickle.load(input)
  37.     print(square.name)
  38.     print(square.x)
  39.     print(square.y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement