Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to write and read class objects to binary file in Python

1 Answer

0 votes
import pickle

class Product(object):
    def __init__(self, pcode, pname, price):
        self.pcode = pcode
        self.pname = pname
        self.price = price

with open('product_file.dat', 'wb') as output:
    obj1 = Product(98742, "Dell XPS 15 laptop 15.6 inch", 1964.43)
    pickle.dump(obj1, output, pickle.HIGHEST_PROTOCOL)

    obj2 = Product(67398, "Dell XPS 13 7390 Laptop 13.3 inch", 1499.99)
    pickle.dump(obj2, output, pickle.HIGHEST_PROTOCOL)

    obj3 = Product(79913, "Apple MacBook Pro 16-Inch 16GB RAM 1TB Storage", 2562.41)
    pickle.dump(obj3, output, pickle.HIGHEST_PROTOCOL)

del obj1
del obj2
del obj3

with open('product_file.dat', 'rb') as input:
    obj1 = pickle.load(input)
    print(obj1.pcode, obj1.pname, obj1.price)
    obj2 = pickle.load(input)
    print(obj2.pcode, obj2.pname, obj2.price)
    obj3 = pickle.load(input)
    print(obj3.pcode, obj3.pname, obj3.price)



'''
run:
 
98742 Dell XPS 15 laptop 15.6 inch 1964.43
67398 Dell XPS 13 7390 Laptop 13.3 inch 1499.99
79913 Apple MacBook Pro 16-Inch 16GB RAM 1TB Storage 2562.41

'''

 



answered Feb 13, 2020 by avibootz
edited Feb 13, 2020 by avibootz

Related questions

1 answer 202 views
2 answers 221 views
1 answer 129 views
1 answer 135 views
...