1. Saving and Loading a List
This program saves a list to a file and then loads it back.
import pickle
my_list = ['apple', 'banana', 'cherry']
with open('list.pkl', 'wb') as file:
pickle.dump(my_list, file)
with open('list.pkl', 'rb') as file:
loaded_list = pickle.load(file)
print("Loaded List:", loaded_list)
#source code --> clcoding.com
Loaded List: ['apple', 'banana', 'cherry']
2. Saving and Loading a Dictionary
This program demonstrates saving a dictionary to a file and loading it back.
import pickle
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('dict.pkl', 'wb') as file:
pickle.dump(my_dict, file)
with open('dict.pkl', 'rb') as file:
loaded_dict = pickle.load(file)
print("Loaded Dictionary:", loaded_dict)
#source code --> clcoding.com
Loaded Dictionary: {'name': 'John', 'age': 30, 'city': 'New York'}
3. Saving and Loading a Custom Object
This program saves an instance of a custom class to a file and loads it back.
import pickle
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
person = Person('Alice', 25)
with open('person.pkl', 'wb') as file:
pickle.dump(person, file)
with open('person.pkl', 'rb') as file:
loaded_person = pickle.load(file)
print("Loaded Person:", loaded_person)
#source code --> clcoding.com
Loaded Person: Person(name=Alice, age=25)
4. Saving and Loading a Tuple
This program saves a tuple to a file and loads it back.
import pickle
my_tuple = (10, 20, 30, 'Hello')
with open('tuple.pkl', 'wb') as file:
pickle.dump(my_tuple, file)
with open('tuple.pkl', 'rb') as file:
loaded_tuple = pickle.load(file)
print("Loaded Tuple:", loaded_tuple)
#source code --> clcoding.com
Loaded Tuple: (10, 20, 30, 'Hello')
5. Saving and Loading Multiple Objects
This program saves multiple objects to a single file and loads them back.
import pickle
list_data = [1, 2, 3]
dict_data = {'a': 1, 'b': 2}
string_data = "Hello, World!"
with open('multiple.pkl', 'wb') as file:
pickle.dump(list_data, file)
pickle.dump(dict_data, file)
pickle.dump(string_data, file)
with open('multiple.pkl', 'rb') as file:
loaded_list = pickle.load(file)
loaded_dict = pickle.load(file)
loaded_string = pickle.load(file)
print("Loaded List:", loaded_list)
print("Loaded Dictionary:", loaded_dict)
print("Loaded String:", loaded_string)
#source code --> clcoding.com
Loaded List: [1, 2, 3]
Loaded Dictionary: {'a': 1, 'b': 2}
Loaded String: Hello, World!
0 Comments:
Post a Comment